unity基於TCP的socket通訊實現“群聊”功能
阿新 • • 發佈:2019-01-22
一般遊戲都有內建聊天系統,socket 也是常見網路通訊方式之一,現在使用 socket 基於 TCP 實現遊戲中“群聊”功能。
老規矩,先上效果圖:
客戶端:可以同時開啟多個
服務端:
接下來上程式碼:
服務端:
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net.Sockets; using System.Net; using System.Threading; namespace Socket_Server // 服務端 { class Program { static List<Socket> socketlist = new List<Socket>(); static void Main(string[] args) { // 例項化 socket Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress iP = new IPAddress(new byte[] { 192,168,0,114}); int port = 6000; IPEndPoint point = new IPEndPoint(iP, port); // 繫結 ip 和 port server.Bind(point); server.Listen(10); // 開啟監聽 Console.WriteLine("【系統提示:伺服器開啟成功...】"); server.BeginAccept(new AsyncCallback(AcceptClient), server); Console.ReadKey(); } static void AcceptClient(IAsyncResult iar) { Socket server = iar.AsyncState as Socket; Socket client = server.EndAccept(iar); // 儲存非同步連結的客戶端 Console.WriteLine("【系統提示:有新的客戶端連結進來...】"); socketlist.Add(client); Console.WriteLine("【客戶端IP:】"+client.RemoteEndPoint); string msg = "系統資訊:歡迎來到聯盟"; byte[] data = Encoding.UTF8.GetBytes(msg); client.Send(data); // 傳送給客戶端 Thread th = new Thread(ReceiveMsg); // 開啟客戶端執行緒 th.Start(client); server.BeginAccept(new AsyncCallback(AcceptClient), server); } // 接受訊息 static void ReceiveMsg(object obj) { Socket socket = obj as Socket; while (true) { byte[] buffer = new byte[1024]; int length = 0; try { length = socket.Receive(buffer); } catch (Exception e) { Console.WriteLine("Exception: " + e.Message); IPEndPoint point = socket.RemoteEndPoint as IPEndPoint; string ipEndpoint = point.Address.ToString(); Console.WriteLine(ipEndpoint + ":退出..."); socketlist.Remove(socket); SendMsgToAll(ipEndpoint + ":有客戶端退出..."); // 呼叫群發訊息 break; } string resMsg = Encoding.UTF8.GetString(buffer, 0, length); IPEndPoint IEP = socket.RemoteEndPoint as IPEndPoint; string ip = IEP.Address.ToString(); string time = DateTime.Now.ToString(); resMsg = "[" + ip + " " + time + "]" + ": \n" + resMsg; Console.WriteLine(resMsg); SendMsgToAll(resMsg); } } // 群發訊息 static void SendMsgToAll(string resMsg) { // 把就收到的訊息群發出去 for (int i = 0; i < socketlist.Count; i++) { socketlist[i].Send(Encoding.UTF8.GetBytes(resMsg)); } } } }
客戶端:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Text;
public class Chat : MonoBehaviour {
Button send;
InputField msgIput;
Text showMsg;
string Message;
Socket client;
void Start () {
send = GameObject.Find("Send").GetComponent<Button>();
msgIput = GameObject.Find("MsgInput").GetComponent<InputField>();
showMsg = GameObject.Find("ShowMsg").GetComponent<Text>();
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client.Connect(new IPEndPoint(IPAddress.Parse("192.168.0.114"), 6000));
send.onClick.AddListener(SendBtnOnClick);
Thread th = new Thread(new ThreadStart(ReceiveMsg));
th.Start();
}
void Update () {
showMsg.text = Message;
}
void OnDestroy()
{
client.Close();
}
void SendBtnOnClick()
{
client.Send(Encoding.UTF8.GetBytes(msgIput.text));
msgIput.text = "";
}
void ReceiveMsg()
{
while (true)
{
byte[] buffer = new byte[1024];
int length = client.Receive(buffer);
string resMsg = "\n" + Encoding.UTF8.GetString(buffer, 0, length);
string str = showMsg.text;
Debug.Log("收到:" + resMsg);
Message = str + resMsg;
}
}
}
基層實現原理值得好好鑽研!