客戶端用Unity開發,主要就是搭建一下聊天室的UI界面:輸入框,聊天內容顯示框,發送按鈕
灰色背景的就是Message,也就是聊天內容的顯示框,是一個Text類型,這里創建UI方面就不多講了
在Canvas下掛一個ChatManager腳本
using System;
using UnityEngine;
using System.Net.Sockets;
using System.Net;
using UnityEngine.UI;
using System.Text;
public class ChatManager : MonoBehaviour {
private Socket clientSocket;
private Button btn;
private InputField inputField;
private Text showMessage;
private byte[] data = new byte[1024];
private string msg = "";
void Start()
{
//創建一個socket,綁定和服務器一樣的ip和端口號,然后執行Connect就可以連接上服務器了(服務器已經運行)
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 6688));
btn = transform.Find("Button").GetComponent<Button>();
btn.onClick.AddListener(OnSendClick);
inputField = transform.Find("InputField").GetComponent<InputField>();
showMessage = transform.Find("BG/Message").GetComponent<Text>();
ClientStart();
}
void Update()
{
if(msg!=null && msg != "")
{
showMessage.text += msg+"\n";回調函數不能調用Unity的組件、UI;所以只能在Update里用,而不能直接在ReceiveCallBack(回調函數不屬於Unity的主線程)
msg = "";
}
}
private void OnSendClick() //綁定到發送按鈕的方法
{
if (inputField.text != "")
{
byte[] databytes = Encoding.UTF8.GetBytes(inputField.text);
clientSocket.Send(databytes);
inputField.text = "";
}
}
private void ClientStart() //開始接收從服務器發來的消息
{
clientSocket.BeginReceive(data, 0, 1024,SocketFlags.None, ReceiveCallBack, null);
}
private void ReceiveCallBack(IAsyncResult ar)
{
try
{
if (clientSocket.Connected == false)
{
clientSocket.Close();
return;
}
int len = clientSocket.EndReceive(ar);
string message = Encoding.UTF8.GetString(data, 0, len);
msg = message;
ClientStart(); //重復接收從服務器發來的信息
}
catch(Exception e)
{
Debug.Log("ReceiveCallBack:" + e);
}
}
void OnDestroy()
{
clientSocket.Close();
}
}