C#中Socket与Unity相结合示例代码
前言
初步接触了Socket,现使其与Unity相结合,做成一个简单的客户端之间可以互相发送消息的一个Test。下面话不多说了,来一起看看详细的介绍吧。
方法如下:
首先,是服务端的代码。
创建一个连接池,用于存储客户端的数量。
usingSystem; usingSystem.Net; usingSystem.Net.Sockets; usingSystem.Collections; usingSystem.Collections.Generic; namespaceServer { //////对象池 /// publicclassConn { //常量,用于表示传输的字节最大数量,最大接收的字节数 publicconstintbuffer_Size=1024; //Socket publicSocketsocket; //是否连接 publicboolisUse=false; //传输数组,用来存储接受到的数据 publicbyte[]readBuff=newbyte[buffer_Size]; publicintbuffCount=0; //////构造函数 /// publicConn() { readBuff=newbyte[buffer_Size]; } //////初始化 /// ///publicvoidInit(Socketsocket) { this.socket=socket; isUse=true; buffCount=0; } /// ///缓冲区剩下的字节数 /// ///publicintBuffRemain() { returnbuffer_Size-buffCount; } /// ///获得客户端地址 /// ///publicstringGetAdress() { if(!isUse) { return"无法获得地址"; } else { returnsocket.RemoteEndPoint.ToString(); } } /// ///关闭连接 /// publicvoidClose() { if(!isUse) { return; } else { Console.WriteLine("断开连接"+GetAdress()); socket.Close(); isUse=false; } } } }
对象池创建完成后,需要在创建一个连接类,用来维护客户端的连接。
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Net; usingSystem.Net.Sockets; namespaceServer { classServ { //监听套接字 publicSocketlistenfd; //客户端链接 publicConn[]conns; //最大的连接数量 publicintmaxConn=50; //获取链接池索引,返回负数表示获取失败 publicintNewIndex() { if(conns==null) { return-1; } for(inti=0;i最后是创建一个Unity的工程,搭建一个简单的页面,通过下面的代码你可以了解需要哪些组件
usingUnityEngine; usingSystem.Collections; usingSystem.Net; usingSystem.Net.Sockets; usingUnityEngine.UI; usingSystem.Collections.Generic; usingSystem; publicclassnet:MonoBehaviour { //ip和端口 publicInputFieldhostInput; publicInputFieldportInput; //显示客户端接受的消息 publicTextrecvText; publicstringrecvStr; //显示客户端IP和端口 publicTextclientText; //聊天输入框 publicInputFieldTextInput; Socketsocket; constintbuffer_Size=1024; publicbyte[]readBuff=newbyte[buffer_Size]; voidFixedUpdate() { recvText.text=recvStr; } //连接服务器(需要一个Button触发) publicvoidConnetion() { recvText.text=""; socket=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); stringhost=hostInput.text; intport=int.Parse(portInput.text); socket.Connect(host,port); clientText.text="客户端地址:"+socket.LocalEndPoint.ToString(); socket.BeginReceive(readBuff,0,buffer_Size,SocketFlags.None,ReceiveCb,socket); } //////接受数据 /// ///publicvoidReceiveCb(IAsyncResultar) { try { intcount=socket.EndReceive(ar); stringstr=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(SocketExceptionex) { Debug.Log(ex); } } /// ///发送数据,(需要一个Button触发) /// publicvoidSend() { stringstr=TextInput.text; byte[]tex=System.Text.Encoding.UTF8.GetBytes(str); try { socket.Send(tex); } catch(SocketExceptionex) { Debug.Log(ex); } } }以上内容出自罗培羽老师《unity3d网络游戏实战》一书。
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对毛票票的支持。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。