服务器端程序
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace 聊天室_服务器端_TCP
{
class Program
{
//存放客户端
static List<Client> clientList = new List<Client>(); //广播消息
public static void BroadCastMessage(string message)
{
//创建未连接的list
var notConnectedList = new List<Client>();
foreach(Client client in clientList)
{
if (client.Connected) //给所有连接的客户端发送消息;
client.SendMessage(message);
else //把未连接的客户端加入list
{
notConnectedList.Add(client);
}
}
//移除未连接的客户端
foreach(var temp in notConnectedList)
{
clientList.Remove(temp);
}
} static void Main(string[] args)
{
//实例化服务器端Socket并指定IP地址类型(IPV4),套接字类型(流类型),通信协议(TCP)
Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); //绑定终端(设置IP地址,端口号(范围为0-65535之间随意取,为避免端口号已被其他软件占用,可以取大点))
tcpServer.Bind(new IPEndPoint(IPAddress.Parse("192.168.0.107"), )); //开始监听,等待客户端接入,接入后执行后续操作
tcpServer.Listen();
Console.WriteLine("开始监听"); //循环等待客户端接入
while (true)
{ Socket ClientSocket = tcpServer.Accept();
Console.WriteLine("一个客户端连接进来了");
Client client = new Client(ClientSocket);
clientList.Add(client);
} }
}
}
Main
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks; namespace 聊天室_服务器端_TCP
{
public class Client
{
private Socket clientsocket;
private Thread t; //线程
private byte[] data = new byte[];
public Client(Socket s)
{
this.clientsocket = s; //启动一个线程,处理客户端数据接收
t = new Thread(ReceiveMessage);
t.Start();
} private void ReceiveMessage()
{
//一直接收客户端数据
while(true)
{
if(clientsocket.Poll(,SelectMode.SelectRead))
{
clientsocket.Close();
break;
}
int length= clientsocket.Receive(data);
string message = Encoding.UTF8.GetString(data, , length);
//接收到数据时,要把这个数据分发到客户端
//广播消息
Program.BroadCastMessage(message);
Console.WriteLine("收到消息:" + message);
}
} //发送消息给客户端
public void SendMessage(string message)
{
byte[] data = Encoding.UTF8.GetBytes(message);
clientsocket.Send(data);
} //判断是否连接
public bool Connected
{
get { return clientsocket.Connected; }
}
}
}
Client类
客户端
using System.Collections;
using System.Collections.Generic;
using System.Net.Sockets;
using UnityEngine;
using System.Net;
using System.Text;
using UnityEngine.UI;
using System.Threading; public class ChatManger : MonoBehaviour { public string ipaddress = "192.168.0.107";
public int port = ;
public Text Input; //InputField中显示输入的text
public Text Label; //聊天室显示的text private Socket client_socket;
private Thread t;
private byte[] data = new byte[]; //数据容器
private string message = ""; //消息容器
// Use this for initialization
void Start () {
OnConnectedToServer();
} // Update is called once per frame
void Update () {
if(message!=""&&message!=null)
{
Label.text += "\n" + message;
message = "";
}
} //连接至服务器,并创建一个新线程用于接受消息
public void OnConnectedToServer()
{
client_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
client_socket.Connect(new IPEndPoint(IPAddress.Parse(ipaddress),port)); t = new Thread(ReceiveMessage);
t.Start();
} //接收消息
public void ReceiveMessage()
{
while(true)
{
if (client_socket.Poll(, SelectMode.SelectRead))
{
client_socket.Close();
break;
}
int length = client_socket.Receive(data);
message = Encoding.UTF8.GetString(data, , length);
//Label.text += "\n" + message; unity不允许在单独的线程里去操控其组件
}
}
//发送消息
public new void SendMessage(string message)
{
byte[] data = Encoding.UTF8.GetBytes(message);
client_socket.Send(data);
}
//点击发送按钮
public void OnSendButtonClick()
{ SendMessage(Input.text);
Input.GetComponentInParent<InputField>().text = "";
} //当Mono被销毁时调用此方法
private void OnDestroy()
{
client_socket.Shutdown(SocketShutdown.Both);
client_socket.Close();
}
}
客户端代码