Unity聊天室实现
来源:互联网 发布:cgi加载java class 编辑:程序博客网 时间:2024/06/06 06:54
本文的通信协议采用的基于TCP协议实现的。然后通过Unity的NGUI插件,实现聊天室场景。把Unity作为客户端,服务器端以C#实现的。实现效果如下图:
上述效果,是开启了两个客户端,然后与服务器通信。思路大致是:首先服务器先接收数据,然后再将客户端发来的消息广播出去。
具体代码如下:
C#服务器端:
Client.cs:处理每个客户端的通信逻辑
using System;using System.Net.Sockets;using System.Text;using System.Threading;namespace _010_聊天室_socket_tcp服务器端{ class Client { private Socket clientSocket; private Thread t; //定义成字段,方便管理该线程 private byte[] data = new byte[1024]; public Client(Socket s) { this.clientSocket = s; //启动一个线程处理客户端的数据接收 t = new Thread(ReceiveMessage); t.Start(); } private void ReceiveMessage() { //一直接收客户端的数据 while (true) { //在接收数据之前 判断Socket连接是否断开 if (!clientSocket.Poll(10,SelectMode.SelectRead)) { int length = clientSocket.Receive(data); string message = Encoding.UTF8.GetString(data, 0, length); //TODO:接收到数据的时候要把这个数据分发到客户端 //广播这个消息 Program.BroadCastMessage(message); Console.WriteLine("客户端发来消息:" + message); } else { clientSocket.Close(); break; //跳出循环,终止线程的执行。 } } } public void SendMessage(string message) { byte[] data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); } public bool Connected { get { return clientSocket.Connected; } } }}
Program.cs
using System;using System.Collections.Generic;using System.Net;using System.Net.Sockets;namespace _010_聊天室_socket_tcp服务器端{ class Program { public static List<Client> clientList = new List<Client>(); public static int Count = 0;//判断连接了几个客户端 /// <summary> /// 广播消息 /// </summary> /// <param name="message"></param> public static void BroadCastMessage(string message) { var notConnectedList = new List<Client>(); foreach (var client in clientList) { if(client.Connected) client.SendMessage(message); else { //将断开连接的客户端保存在新建的List集合当中,方便在下次遍历是移除 notConnectedList.Add(client); } } //移除断开连接的客户端 foreach (var temp in notConnectedList) { clientList.Remove(temp); Count--; } } static void Main(string[] args) { //1.新建一个Socket Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Console.WriteLine("Server Running."); //2.绑定端口号 serverSocket.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"),7788 )); //3.服务器端开启监听 serverSocket.Listen(100); //最大的客户端数量为100 //4.循环接收客户端的请求 while (true) { Socket clientSocket = serverSocket.Accept();//此处等待客户端连接,直到有连接才执行下面代码 Console.WriteLine("A client is connected."); //把与每个客户端通信的逻辑(收发消息)放到Client类里面处理 Client client = new Client(clientSocket); clientList.Add(client); Count++; } } }}
U3D客户端代码如下:
using System.Collections;using System.Collections.Generic;using System.Net;using System.Net.Sockets;using System.Text;using System.Threading;using UnityEngine;public class ChatManager : MonoBehaviour{ public UIInput textInput; public UILabel chatLabel; public string ipaddress = "127.0.0.1"; public int port = 7788; private Socket clientSocket; private Thread t; private byte[] data = new byte[1024]; private string message = ""; // Use this for initialization void Start () { ConnectToServer(); } // Update is called once per frame void Update () { if (message != null && message != "") { chatLabel.text += "\n" + message; message = ""; //清空消息 } } void ConnectToServer() { clientSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream, ProtocolType.Tcp); //跟服务器建立连接 clientSocket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress),port)); //创建一个新的线程来不停的接收消息 t = new Thread(ReceiveMessage); t.Start(); } /// <summary> /// 用于循环接收消息 /// </summary> void ReceiveMessage() { while (true) { if(clientSocket.Connected == false) break; int length = clientSocket.Receive(data); message = Encoding.UTF8.GetString(data, 0, length); //Unity不允许在线程里面操作Unity里面的组件,因此需要在Update()方法里面执行 //chatLabel.text += "\n" + message; } } void SendMessage(string message) { byte[] data = Encoding.UTF8.GetBytes(message); clientSocket.Send(data); } public void OnSendButtonClick() { string value = textInput.value; SendMessage(value); textInput.value = ""; } void OnDestroy() { clientSocket.Shutdown(SocketShutdown.Both); clientSocket.Close(); //关闭连接 }}
阅读全文
0 0
- Unity聊天室实现
- 【Unity】Unity3D教程:实现基于Socket通讯的公共聊天室
- Unity基于TCP/IP的小聊天室实现
- 【Unity】简单聊天室功能的实现方法教程
- socket/TCP/UDP基础及Unity聊天室的实现
- unity 搭建聊天室
- unity聊天室服务器端
- unity制作聊天室界面
- 聊天室实现
- Unity简单多人聊天室
- Photon服务器引擎(二)socket/TCP/UDP基础及Unity聊天室的实现
- Photon服务器引擎(二)socket/TCP/UDP基础及Unity聊天室的实现
- 简单网络聊天室实现
- Ajax+servlet实现聊天室
- Socket实现手机聊天室
- Java 实现QQ聊天室
- UDP实现聊天室
- 聊天室功能实现
- Ubuntu 16.04 apt-get搭建LAMP环境
- JAVA中的this关键字
- Math中的round、ceil、floor的功能。
- 堆排序
- bzoj1299: [LLH邀请赛]巧克力棒
- Unity聊天室实现
- 【贪心+DP】BZOJ1899(Zjoi2004)[Lunch 午餐]题解
- Windows编程入门-设备环境的信息
- linux大文件分割与合并
- cxgrid只能看见一条记录
- uva 1592Database
- TCP连接和断开 “三次握手和四次挥手”
- 当有U盘或摄像头插进USB口时, 程序如何检测到
- 回溯法与分支界定法的区别