unity3d游戏开发之实现基于Socket通讯的公共聊天室

整理文档很辛苦,赏杯茶钱您下走!

免费阅读已结束,点击下载阅读编辑剩下 ...

阅读已结束,您可以下载文档离线阅读编辑

资源描述

由于这段时间比较忙,所以也很久没发布过新的教程,这几天刚好要为一个项目写服务端程序,所以顺便也在Unity3d里面实现了一个简单的客户端,多个客户端一同使用就是一个简单的公共聊天室了。服务端为一个控制台程序使用C#实现,当然,在Unity3d中也相应地使用了C#语言实现客户端,服务端和客户端能实现消息的互通,当服务端接收到某客户端发送过来的消息时将会对客户端列表成员进行广播,这是公共聊天室的最基本的形式。Socket通讯是网络游戏最为基础的知识,因此这个实例能向有志投身于网游行业的初学者提供指导意义。这篇文章来自狗刨学习网Program.cs1.usingSystem;2.usingSystem.Collections.Generic;3.usingSystem.Linq;4.usingSystem.Text;5.usingSystem.Net.Sockets;6.7.namespaceTestServer8.{9.classProgram10.{11.//设置连接端口12.constintportNo=500;13.14.staticvoidMain(string[]args)15.{16.//初始化服务器IP17.System.Net.IPAddresslocalAdd=System.Net.IPAddress.Parse(127.0.0.1);18.19.//创建TCP侦听器20.TcpListenerlistener=newTcpListener(localAdd,portNo);21.22.listener.Start();23.24.//显示服务器启动信息25.Console.WriteLine(Serverisstarting...\n);26.27.//循环接受客户端的连接请求28.while(true)29.{30.ChatClientuser=newChatClient(listener.AcceptTcpClient());31.32.//显示连接客户端的IP与端口33.Console.WriteLine(user._clientIP+isjoined...\n);34.}35.}36.}37.}复制代码ChatClient.cs1.usingSystem;2.usingSystem.Collections.Generic;3.usingSystem.Linq;4.usingSystem.Text;5.usingSystem.Collections;6.usingSystem.Net.Sockets;7.8.namespaceTestServer9.{10.classChatClient11.{12.publicstaticHashtableALLClients=newHashtable();//客户列表13.14.privateTcpClient_client;//客户端实体15.publicstring_clientIP;//客户端IP16.privatestring_clientNick;//客户端昵称17.18.privatebyte[]data;//消息数据19.20.privateboolReceiveNick=true;21.22.publicChatClient(TcpClientclient)23.{24.this._client=client;25.26.this._clientIP=client.Client.RemoteEndPoint.ToString();27.28.//把当前客户端实例添加到客户列表当中29.ALLClients.Add(this._clientIP,this);30.31.data=newbyte[this._client.ReceiveBufferSize];32.33.//从服务端获取消息34.client.GetStream().BeginRead(data,0,System.Convert.ToInt32(this._client.ReceiveBufferSize),ReceiveMessage,null);35.}36.37.//从客戶端获取消息38.publicvoidReceiveMessage(IAsyncResultar)39.{40.intbytesRead;41.42.try43.{44.lock(this._client.GetStream())45.{46.bytesRead=this._client.GetStream().EndRead(ar);47.}48.49.if(bytesRead1)50.{51.ALLClients.Remove(this._clientIP);52.53.Broadcast(this._clientNick+hasleftthechat);54.55.return;56.}57.else58.{59.stringmessageReceived=System.Text.Encoding.ASCII.GetString(data,0,bytesRead);60.61.if(ReceiveNick)62.{63.this._clientNick=messageReceived;64.65.Broadcast(this._clientNick+hasjoinedthechat.);66.67.//this.sendMessage(hello);68.69.ReceiveNick=false;70.}71.else72.{73.Broadcast(this._clientNick++messageReceived);74.75.}76.}77.78.lock(this._client.GetStream())79.{80.this._client.GetStream().BeginRead(data,0,System.Convert.ToInt32(this._client.ReceiveBufferSize),ReceiveMessage,null);81.}82.}83.catch(Exceptionex)84.{85.ALLClients.Remove(this._clientIP);86.87.Broadcast(this._clientNick+hasleftthechat.);88.}89.}90.91.//向客戶端发送消息92.publicvoidsendMessage(stringmessage)93.{94.try95.{96.System.Net.Sockets.NetworkStreamns;97.98.lock(this._client.GetStream())99.{100.ns=this._client.GetStream();101.}102.103.//对信息进行编码104.byte[]bytesToSend=System.Text.Encoding.ASCII.GetBytes(message);105.106.ns.Write(bytesToSend,0,bytesToSend.Length);107.ns.Flush();108.}109.catch(Exceptionex)110.{111.112.}113.}114.115.//向客户端广播消息116.publicvoidBroadcast(stringmessage)117.{118.Console.WriteLine(message);119.120.foreach(DictionaryEntrycinALLClients)121.{122.((ChatClient)(c.Value)).sendMessage(message+Environment.NewLine);123.}124.}125.126.}127.}复制代码Unity3d客户端的代码ClientHandler.cs:1.usingUnityEngine;2.usingSystem.Collections;3.4.usingSystem;5.usingSystem.Collections.Generic;6.usingSystem.ComponentModel;7.usingSystem.Text;8.usingSystem.Net.Sockets;9.10.publicclassClientHandler:MonoBehaviour11.{12.constintportNo=500;13.privateTcpClient_client;14.byte[]data;15.16.//Usethisforinitialization17.voidStart()18.{19.20.}21.22.//Updateiscalledonceperframe23.voidUpdate()24.{25.26.}27.28.publicstringnickName=;29.publicstringmessage=;30.publicstringsendMsg=;31.32.voidOnGUI()33.{34.nickName=GUI.TextField(newRect(10,10,100,20),nickName);35.message=GUI.TextArea(newRect(10,40,300,200),message);36.sendMsg=GUI.TextField(newRect(10,250,210,20),sendMsg);37.38.if(GUI.Button(newRect(120,10,80,20),Connect))39.{40.//Debug.Log(hello);41.42.this._client=newTcpClient();43.this._client.Connect(127.0.0.1,portNo);44.45.data=newbyte[this._client.ReceiveBufferSize];46.47.//SendMessage(txtNick.Text);48.SendMessage(nickName);49.50.this._client.GetStream().BeginRead(data,0,System.Convert.ToInt32(this._client.ReceiveBufferSize),ReceiveMessage,null);51.};52.53.if(GUI.Button(newRect(230,250,80,20),Send))54.{55.SendMessage(sendMsg);56.sendMsg=;57.};58.}59.60.publicvoidSendMessage(stringmessage)61.{62.try63.{64.NetworkStreamns=this._client.GetStream();65.66.byte[]data=System.Text.Encoding.ASCII.GetBytes(message);67.68.ns.Write(data,0,data.Length);69.ns.Flush();70.}71.catch(Exceptionex)72.{73.//MessageBox.Show(ex.ToString());74.}75.}76.77.publicvoidReceiveMessage(IAsyncResultar)78.{79.try80.{81.intbytesRead;82.83.bytesRead=this._client.GetStream().EndRead(ar);84.85.if(bytesRead1)86.{87.return;88.}89.else90.{91.92.Debug.Log(System.Text.Encoding.ASCII.GetString(data,0,bytesRead)

1 / 9
下载文档,编辑使用

©2015-2020 m.777doc.com 三七文档.

备案号:鲁ICP备2024069028号-1 客服联系 QQ:2149211541

×
保存成功