Unity实现聊天室功能
本文实例为大家分享了Unity实现聊天室功能的具体代码,供大家参考,具体内容如下
简单聊天室功能,客户端发送消息后,服务器接收到消息后分发到其它客户端上并显示聊天内容
聊天室服务器
服务器需要有以下几个步骤
1、确定Socket协议类型(采用TCP协议或者UDP协议)
2、绑定服务器的IP地址和端口号
3、设置最大监听数量
4、等到连接并处理消息
由于服务器属于一对多的处理关系,因为我们需要用线程来监听消息:
classClient
{
privateSocketclientSocket;
privateThreadt;
publicboolConnected
{
get
{
returnclientSocket.Connected;
}
}
privatebyte[]data=newbyte[1024];//数据容器
publicClient(Socketclient)
{
clientSocket=client;
//启动一个线程,处理客户端的接受
t=newThread(ReceiveMsg);
t.Start();
}
privatevoidReceiveMsg()
{
while(true)
{
//在接收数据之前,判断Socket连接是否断开
if(!clientSocket.Connected)
{
clientSocket.Close();
break;//跳出循环终止线程的执行
}
intlength=clientSocket.Receive(data);
stringmsg=Encoding.UTF8.GetString(data,0,length);
//服务端接收数据后,要将数据分发到客户端
//广播消息
Program.BroadcastMsg(msg);
}
}
publicvoidSendMsg(stringmsg)
{
byte[]data=Encoding.UTF8.GetBytes(msg);
clientSocket.Send(data);
}
}
服务器主要代码:
classProgram
{
staticListclients=newList();
//本机IP:192.168.100.172
staticvoidMain(string[]args)
{
SockettcpServer=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
tcpServer.Bind(newIPEndPoint(IPAddress.Parse("192.168.100.172"),7788));
tcpServer.Listen(5000);
Console.WriteLine("ServerRunning.......");
while(true)
{
varclientSocket=tcpServer.Accept();
Console.WriteLine("建立连接");
Clientclient=newClient(clientSocket);
clients.Add(client);
}
}
publicstaticvoidBroadcastMsg(stringmsg)
{
varnoConnecteds=newList();
foreach(varclientinclients)
{
if(client.Connected)
{
client.SendMsg(msg);
}
else
{
noConnecteds.Add(client);
}
}
foreach(vardelinnoConnecteds)
{
clients.Remove(del);
}
}
}   
Unity客户端代码
Unity客户端代码就十分简单,监听服务器的消息并显示到界面上即可
usingSystem.Collections;
usingSystem.Collections.Generic;
usingUnityEngine;
usingSystem.Net;
usingSystem.Net.Sockets;
usingSystem.Text;
usingUnityEngine.UI;
usingSystem.Threading;
publicclassChatManager:MonoBehaviour
{
publicstringIP="192.168.100.172";
publicintPort=7788;
privateSocketclient;
privateThreadt;
publicInputFieldinput;
publicButtonsendBtn;
publicTextitem;
publicstringname;
privatestringmsg=string.Empty;
//Startiscalledbeforethefirstframeupdate
voidStart()
{
ConnectedToServer();
sendBtn.onClick.AddListener(()=>{
SendMsg(input.text);
input.text=string.Empty;
});
}
//Updateiscalledonceperframe
voidUpdate()
{
//由于在Unity中不允许在线程中调用UnityAPI,因此需要的Update中刷新显示
if(!string.IsNullOrEmpty(msg))
{
item.text+="\n"+msg;
msg=string.Empty;
}
}
privatevoidConnectedToServer()
{
client=newSocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
client.Connect(newIPEndPoint(IPAddress.Parse(IP),Port));
//创建一个线程用来接收消息
t=newThread(ReceiveMsg);
t.Start();
}
byte[]data=newbyte[1024];
publicvoidReceiveMsg()
{
while(true)
{
if(!client.Connected)
{
break;
}
intlength=client.Receive(data);
msg=Encoding.UTF8.GetString(data,0,length);
}
}
publicvoidSendMsg(stringmsg)
{
byte[]data=Encoding.UTF8.GetBytes(name+":"+msg);
client.Send(data);
}
publicvoidOnDestroy()
{
client.Close();
}
}
实际运行效果(注意需要先启动服务器):
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:czq8825#qq.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。