您好,登錄后才能下訂單哦!
前言
初步接觸了Socket,現使其與Unity相結合,做成一個簡單的客戶端之間可以互相發送消息的一個Test。下面話不多說了,來一起看看詳細的介紹吧。
方法如下:
首先,是服務端的代碼。
創建一個連接池,用于存儲客戶端的數量。
using System; using System.Net; using System.Net.Sockets; using System.Collections; using System.Collections.Generic; namespace Server { /// <summary> /// 對象池 /// </summary> public class Conn { //常量,用于表示傳輸的字節最大數量,最大接收的字節數 public const int buffer_Size = 1024; //Socket public Socket socket; //是否連接 public bool isUse = false; //傳輸數組,用來存儲接受到的數據 public byte[] readBuff = new byte[buffer_Size]; public int buffCount = 0; /// <summary> /// 構造函數 /// </summary> public Conn() { readBuff = new byte[buffer_Size]; } /// <summary> /// 初始化 /// </summary> /// <param name="socket"></param> public void Init(Socket socket) { this.socket = socket; isUse = true; buffCount = 0; } /// <summary> /// 緩沖區剩下的字節數 /// </summary> /// <returns></returns> public int BuffRemain() { return buffer_Size - buffCount; } /// <summary> /// 獲得客戶端地址 /// </summary> /// <returns></returns> public string GetAdress() { if (!isUse) { return "無法獲得地址"; } else { return socket.RemoteEndPoint.ToString(); } } /// <summary> /// 關閉連接 /// </summary> public void Close() { if (!isUse) { return; } else { Console.WriteLine("斷開連接" + GetAdress()); socket.Close(); isUse = false; } } } }
對象池創建完成后,需要在創建一個連接類,用來維護客戶端的連接。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace Server { class Serv { //監聽套接字 public Socket listenfd; //客戶端鏈接 public Conn[] conns; //最大的連接數量 public int maxConn = 50; //獲取鏈接池索引,返回負數表示獲取失敗 public int NewIndex() { if(conns==null) { return -1; } for (int i = 0; i < conns.Length;i++ ) { if(conns[i]==null) { conns[i] = new Conn(); return i; }else if(conns[i].isUse==false) { return i; } } return -1; } //開啟一個服務器 public void Start(string host,int port) { conns = new Conn[maxConn]; for (int i = 0; i < maxConn;i++ ) { conns[i] = new Conn(); } listenfd = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ipAdr = IPAddress.Parse(host); IPEndPoint ipEp = new IPEndPoint(ipAdr, port); //與一個本地終結點相關聯 listenfd.Bind(ipEp); //監聽 listenfd.Listen(maxConn); listenfd.BeginAccept(AcceptCb, listenfd); } //AcceptCb回調 public void AcceptCb(IAsyncResult ar) { try { Socket sSocket = ar.AsyncState as Socket; Socket socket = sSocket.EndAccept(ar); int index = NewIndex(); if(index<0) { socket.Close(); Console.WriteLine("連接已滿"); } else { Conn conn = conns[index]; conn.Init(socket); string adr = conn.GetAdress(); Console.WriteLine("客戶端連接[" + adr + "Conn池ID: " + index); conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn); } listenfd.BeginAccept(AcceptCb, listenfd); }catch(SocketException ex) { Console.WriteLine(ex); } } //ReceiveCb回調 public void ReceiveCb(IAsyncResult ar) { Conn conn = (Conn)ar.AsyncState; try { int count = conn.socket.EndReceive(ar); if(count<=0) { Console.WriteLine("收到:" + conn.GetAdress() + "斷開連接"); conn.Close(); return; } string str = Encoding.UTF8.GetString(conn.readBuff,0,count); Console.WriteLine("接收到[" + conn.GetAdress() + "]數據" + str); byte[] bytes = Encoding.UTF8.GetBytes(str); for (int i = 0; i < conns.Length;i++ ) { if(conns[i]==null) continue; if (!conns[i].isUse) continue; Console.WriteLine("將消息傳送給" + conns[i].GetAdress()); conns[i].socket.Send(bytes); } conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None,ReceiveCb, conn); } catch(SocketException ex) { Console.WriteLine(ex); Console.WriteLine("收到:" + conn.GetAdress() + "斷開連接"); conn.Close(); } } } }
最后是創建一個Unity的工程,搭建一個簡單的頁面,通過下面的代碼你可以了解需要哪些組件
using UnityEngine; using System.Collections; using System.Net; using System.Net.Sockets; using UnityEngine.UI; using System.Collections.Generic; using System; public class net : MonoBehaviour { //ip和端口 public InputField hostInput; public InputField portInput; //顯示客戶端接受的消息 public Text recvText; public string recvStr; //顯示客戶端IP和端口 public Text clientText; //聊天輸入框 public InputField TextInput; Socket socket; const int buffer_Size = 1024; public byte[] readBuff = new byte[buffer_Size]; void FixedUpdate() { recvText.text = recvStr; } //連接服務器(需要一個Button觸發) public void Connetion() { recvText.text = ""; socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); string host = hostInput.text; int port = int.Parse(portInput.text); socket.Connect(host, port); clientText.text = "客戶端地址:"+socket.LocalEndPoint.ToString(); socket.BeginReceive(readBuff, 0, buffer_Size, SocketFlags.None, ReceiveCb,socket); } /// <summary> /// 接受數據 /// </summary> /// <param name="ar"></param> public void ReceiveCb(IAsyncResult ar) { try { int count = socket.EndReceive(ar); string str = System.Text.Encoding.UTF8.GetString(readBuff, 0, count); if (recvStr.Length > 300) recvStr = ""; recvStr += socket.LocalEndPoint.ToString()+str + "\n"; Debug.Log("12346"); socket.BeginReceive(readBuff, 0, buffer_Size, SocketFlags.None, ReceiveCb, socket); }catch(SocketException ex) { Debug.Log(ex); } } /// <summary> /// 發送數據,(需要一個Button觸發) /// </summary> public void Send() { string str = TextInput.text; byte[] tex = System.Text.Encoding.UTF8.GetBytes(str); try { socket.Send(tex); } catch(SocketException ex) { Debug.Log(ex); } } }
以上內容出自羅培羽老師《unity3d網絡游戲實戰》一書。
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對億速云的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。