利⽤C#Socket实现简单聊天室
因为这段时间在学习Socket,所以就试着写了⼀个简单的聊天室。主要分为服务器端和多个客户端。利⽤服务器端作数据中转站,实现消息群发。
1. 服务器端有两个类:
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
namespace 聊天室_Socket_TCP_服务器端
{
class Program
{
static List<Client> clients = new List<Client>();
static List<Client> notClients = new List<Client>();
/// <summary>
/// ⼴播消息
/// </summary>
/// <param name="message"></param>
public static void CastMessageTOAllConnetedClients(string message)
{
foreach (var client in clients)
{
if (client.Conneted)
{
client.CastMessage(message);
}
el
{
郑州枫杨外国语中学
notClients.Add(client);
}
}
foreach (var temp in notClients)
{
clients.Remove(temp);
}
er mapper
}
static void Main(string[] args)
{
Socket tcpSever = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
tcpSever.Bind(new IPEndPoint(IPAddress.Par("192.168.1.2"), 8899));
tcpSever.Listen(100);//监听是否有客户端发起连接
Console.WriteLine("Begin ");
while (true)
{
Socket clientSocket = tcpSever.Accept();
if (clientSocket!=null)
{
Console.WriteLine("A client ");
Client client = new Client(clientSocket);//将每个新创建的连接通信放于client类做通信
clients.Add(client);
}
关于旅游的英语短文}
Console.ReadKey();
}
}
}
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace 聊天室_Socket_TCP_服务器端英文聊天
{
/// <summary>
/// 利⽤该类和客户端做通信
/// </summary>
class Client
{
public Socket clientSocket;
private Thread mesManageTherad;
private byte[] bufffer=new byte[20];
public Client(Socket soc)
{
clientSocket = soc;
//由于消息是不断发送的,需要多次进⾏处理。这⾥开⼀个线程,专门⽤来处理消息。 mesManageTherad = new Thread(MessageSendFromClient);
mesManageTherad.Start();
}
private void MessageSendFromClient()
prescott
{
//开启的线程⼀直检测客户端客户端发过来的消息
while (true)
{
//判断连接是否断开, SelectMode.SelectRead读状态模式。
//poll已断开返回true
if (clientSocket.Poll(10,SelectMode.SelectRead)==true)
{
clientSocket.Clo();
break;//终⽌本线程
}
int byteNum = clientSocket.Receive(bufffer);//从客户端接受消息
string mes = Encoding.UTF8.GetString(bufffer, 0 , byteNum);
Console.WriteLine("客户端发送过来的消息:"+mes);
//⼴播消息出去给每个客户端
Program.CastMessageTOAllConnetedClients(mes);//对CastMessage的⼀层封装 }
}
/// <summary>
/// Send messages to Clients
/// </summary>
public void CastMessage(string message)
{
byte[] data = Encoding.UTF8.GetBytes(message);
clientSocket.Send(data);
}
/// <summary>
/// 判断是否断开连接
/// </summary>
public bool Conneted
{
get
{
return clientSocket.Connected;
}
}
}
nigga}
}
服务器端逻辑:
这⾥的服务器主要负责建⽴连接,接受客户端消息,⼴播客户端发来的消息。
服务器通过socket对象绑定服务器IP和相应端⼝号(端⼝号⾃⼰开,没有被其他软件占⽤就好),通过Listen监听和服务器socket对象的Accept⽅法捕捉连接到服务器的客户端socket,将捕捉到的客户端socket放⼊List集合中⽅便统⼀管理和后⾯的消息群发。
关于捕捉到的客户端socket的逻辑处理放在了Client类中统⼀管理。
Client类将收到客户端的消息进⾏接受,在Client中开启⼀个线程⽤于不断得检测是否有新消息从客户端发送过来,若有消息发送过来则通过CastMessageTOAllConnetedClients⽅法(对socket对象的Send⽅法的封装)发送给每⼀个客户端。
2.客户端
客户端是在Unity中使⽤NGUI插件简单开发的⼀个聊天界⾯。把脚本挂在NGUI控件上即可。客户端主要负责显⽰消息,发送消息,接收消息。
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using UnityEngine;
public class ChatManager : MonoBehaviour {
private string _ipAdress = "192.168.1.2";
private int _port=8899;
EndPoint remotPoint;
Socket clientSocket;
public UIInput buttonInput;
private bool isCanSend=fal;
private string buttonMessage=null;
Thread receiveThread;
byte[] bufferReceive = new byte[1024];
public UILabel chatWindowLable;
private string message = "";//默认为空串
公司内账
// U this for initialization
void Start () {
ConnetToSever(_ipAdress, _port);//与服务器建⽴连接
}
/
/ Update is called once per frame
void Update () {
if (message!=null&&message!="")
{
< += "\n" + message;
message = "";//清空消息
}
}
void ConnetToSever(string ipadress,int port)
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
remotPoint = new IPEndPoint(IPAddress.Par(ipadress),port);
//建⽴连接
clientSocket.Connect(remotPoint);
//因为是⼀直在准备接受的状态,所以开启⼀个线程来负责处理接受消息
receiveThread = new Thread(ReceiveMessageFormSever);
receiveThread.Start();
}
private new void SendMessage(string message)
{
byte [] buffer= Encoding.UTF8.GetBytes(message);
clientSocket.SendTo(buffer,remotPoint);
}
public void OnSendButtonClickS()
{
if (buttonInput.value!=null)
{
buttonMessage = buttonInput.value;
}
el
{
buttonMessage = "输⼊框为空!";
}
SendMessage(buttonMessage);
buttonInput.value = "";
superman}
private void ReceiveMessageFormSever()
{
while (true)
jealousness{
if (clientSocket.Connected)
{
int length = clientSocket.Receive(bufferReceive);
message = Encoding.UTF8.GetString(bufferReceive, 0, length);
/
产品说明翻译
/ps:不要在单独的线程⾥⾯操作unity组件
}
el
{
break;
}
}
}
}
在客户端中同样有⼀个socket对象,这个对象通过ConnetToSever⽅法连接到服务器。在这⾥,假如某个客户端通过输⼊框输⼊⽂本被客户端脚本捕捉,它将以流的⽅式发送到服务器,服务器接受到⽂本,并在服务器端将⽂本群发⾄每个客户端。服务器开设了⼀个线程专门⽤于捕捉客户端发来的消息,
当然,客户端也有相应的线程时刻捕捉服务器发来的消息。消息被客户端捕捉到了,就可以显⽰在各⾃的客户端界⾯上了。
学习后的⼀点总结,不喜勿喷~