C#聊天室雏形
52unity 人气:0程序使用的控制台的黑窗口模拟程序,第一次涉及网络编程,写出来方便以后查阅,代码很简单
首先是服务器端的代码:
public class ServerControl { private Socket serverSocket; public ServerControl() { serverSocket = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp); } public void Start() { serverSocket.Bind(new IPEndPoint(IPAddress.Any, 12312)); //设置接收任何ip serverSocket.Listen(10); //最大挂起数 Console.WriteLine("服务器启动成功"); } }
主程序:
static void Main(string[] args) { ServerControl server = new ServerControl(); server.Start(); Console.ReadKey(); }
下面是客户端代码:
public class ClientControl { Socket clientSocket; public ClientControl() { clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); } public void Connect(string ip, int port) { clientSocket.Connect(ip, port); Console.WriteLine("连接服务器成功"); } }
客户端的调用代码:
static void Main(string[] args) { ClientControl client = new ClientControl(); client.Connect("127.0.0.1",12312); Console.ReadKey(); }
此时客户端就可以顺利连接到服务器,下一步是在服务器上显示是谁连接到服务器了很简单只需要在服务器端加一个方法来检测:
private void Accept() { //接收客户端方法,会挂起当前线程 Socket client = serverSocket.Accept(); IPEndPoint point = client.RemoteEndPoint as IPEndPoint; Console.WriteLine(point.Address + "[" + point.Port + "]连接成功"); Accept(); //尾递归 }
因为要在服务器启动就要去检测有没有连接到服务器的ip,所以需要在start方法中开辟一个新的线程来调用Accept方法
Thread threadAccept = new Thread(Accept); //接收一个委托方法 threadAccept.IsBackground = true; //设置为后台线程 threadAccept.Start();
下一步就是客户端要往服务器发送消息
客户端的ClientControl类代码:
public void Send(string msg) { clientSocket.Send(Encoding.UTF8.GetBytes(msg)); }
客户端主程序调用代码:
Console.WriteLine("请输入要发送的内容, 输入exit退出:"); string msg = Console.ReadLine(); while (msg != "exit") { client.Send(msg); msg = Console.ReadLine(); }
下一步就是要在服务器接收客户端的输入内容
private void Receive(object obj) { Socket client = obj as Socket; IPEndPoint point = client.RemoteEndPoint as IPEndPoint; try //防止客户端异常断开抛异常 { byte[] msg = new byte[1024]; int msglen = client.Receive(msg); Console.WriteLine(point.Address + "[" + point.Port + "]:" + Encoding.UTF8.GetString(msg, 0, msglen)); client.Send(Encoding.UTF8.GetBytes(Encoding.UTF8.GetString(msg, 0, msglen))); //这个地方加了个小功能,就是客户端来一个消息 服务器给他发回去同样的,可以去掉 Receive(client); //尾递归 } catch { Console.WriteLine(point.Address + "[" + point.Port + "]:" + "已经断开"); }
这个方法执行同样会挂起线程,所以要开辟一个新的线程,因为这是接收客户端的消息,所以这个新线程要写在刚才写的Accept方法里面
Thread threadReceive = new Thread(Receive); threadReceive.IsBackground = true; threadReceive.Start(client);
附加:
刚才不是写了一个服务器接收到消息,会给客户端返回一个相同的消息,所以还要在客户端接收服务器的消息,方法和在服务器端接收大同小异
private void Receive() { try { byte[] msg = new byte[1024]; int msglen = clientSocket.Receive(msg); Console.WriteLine("服务器说:" + Encoding.UTF8.GetString(msg)); Receive(); } catch { Console.WriteLine("服务器已经断开"); } }
以为一连上就要去检测服务器有没有消息,所以开辟一个线程 写在客户端的 connect方法中
Thread threadReceive = new Thread(Receive); threadReceive.IsBackground = true; threadReceive.Start();
好了 ,一个最简单的聊天室就算写完了
想多人登陆 就在vs中找到客户端的debug文件夹 找到exe文件运行
加载全部内容