本文的通信协议采用的基于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(); //关闭连接
}
}