C#中Socket與Unity相結(jié)合示例代碼
前言
初步接觸了Socket,現(xiàn)使其與Unity相結(jié)合,做成一個簡單的客戶端之間可以互相發(fā)送消息的一個Test。下面話不多說了,來一起看看詳細(xì)的介紹吧。
方法如下:
首先,是服務(wù)端的代碼。
創(chuàng)建一個連接池,用于存儲客戶端的數(shù)量。
using System; using System.Net; using System.Net.Sockets; using System.Collections; using System.Collections.Generic; namespace Server { /// <summary> /// 對象池 /// </summary> public class Conn { //常量,用于表示傳輸?shù)淖止?jié)最大數(shù)量,最大接收的字節(jié)數(shù) public const int buffer_Size = 1024; //Socket public Socket socket; //是否連接 public bool isUse = false; //傳輸數(shù)組,用來存儲接受到的數(shù)據(jù) public byte[] readBuff = new byte[buffer_Size]; public int buffCount = 0; /// <summary> /// 構(gòu)造函數(shù) /// </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> /// 緩沖區(qū)剩下的字節(jié)數(shù) /// </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> /// 關(guān)閉連接 /// </summary> public void Close() { if (!isUse) { return; } else { Console.WriteLine("斷開連接" + GetAdress()); socket.Close(); isUse = false; } } } }
對象池創(chuàng)建完成后,需要在創(chuàng)建一個連接類,用來維護(hù)客戶端的連接。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using System.Net.Sockets; namespace Server { class Serv { //監(jiān)聽套接字 public Socket listenfd; //客戶端鏈接 public Conn[] conns; //最大的連接數(shù)量 public int maxConn = 50; //獲取鏈接池索引,返回負(fù)數(shù)表示獲取失敗 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; } //開啟一個服務(wù)器 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); //與一個本地終結(jié)點(diǎn)相關(guān)聯(lián) listenfd.Bind(ipEp); //監(jiān)聽 listenfd.Listen(maxConn); listenfd.BeginAccept(AcceptCb, listenfd); } //AcceptCb回調(diào) 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回調(diào) 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() + "]數(shù)據(jù)" + 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(); } } } }
最后是創(chuàng)建一個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; } //連接服務(wù)器(需要一個Button觸發(fā)) 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> /// 接受數(shù)據(jù) /// </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> /// 發(fā)送數(shù)據(jù),(需要一個Button觸發(fā)) /// </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); } } }
以上內(nèi)容出自羅培羽老師《unity3d網(wǎng)絡(luò)游戲?qū)崙?zhàn)》一書。
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持。
相關(guān)文章
C#強(qiáng)制轉(zhuǎn)換和嘗試轉(zhuǎn)換的方法
這篇文章主要為大家詳細(xì)介紹了C#強(qiáng)制轉(zhuǎn)換和嘗試轉(zhuǎn)換的方法,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09WPF利用ValueConverter實(shí)現(xiàn)值轉(zhuǎn)換器
值轉(zhuǎn)換器在WPF開發(fā)中是非常常見的,值轉(zhuǎn)換器可以幫助我們很輕松地實(shí)現(xiàn),界面數(shù)據(jù)展示的問題。本文將通過WPF?ValueConverter實(shí)現(xiàn)簡單的值轉(zhuǎn)換器,希望對大家有所幫助2023-03-03C#中使用ArrayPool和MemoryPool實(shí)例
對資源的可復(fù)用是提升應(yīng)用程序性能的一個非常重要的手段,比如本篇要分享的 ArrayPool 和 MemoryPool,它們就有效的減少了內(nèi)存使用和對GC的壓力,從而提升應(yīng)用程序性能。感興趣的可以了解一下2021-05-05C#使用DropDownList綁定添加新數(shù)據(jù)的方法匯總
這篇文章主要介紹了C#使用DropDownList綁定添加新數(shù)據(jù)的方法匯總的相關(guān)資料,需要的朋友可以參考下2016-03-03