用c#写个基于socket的简易聊天项目
时间: 2023-12-17 17:04:47 浏览: 77
Socket-based-chat-room,窗体c#源码,c#
非常感谢您的问题。以下是一个基于 Socket 的简易聊天项目的示例代码:
服务端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Server {
public static void Main () {
// 建立服务端 Socket,监听本地 IP 地址和指定端口号
Socket serverSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint (IPAddress.Parse ("127.0.0.1"), 8888);
serverSocket.Bind (ipEndPoint);
serverSocket.Listen (10);
Console.WriteLine ("等待客户端连接...");
while (true) {
// 接受客户端连接请求
Socket clientSocket = serverSocket.Accept ();
Console.WriteLine ("客户端已连接");
// 接收消息
byte[] buffer = new byte[1024];
int count = clientSocket.Receive (buffer);
string message = Encoding.UTF8.GetString (buffer, 0, count);
Console.WriteLine ("客户端:" + message);
// 发送消息
string response = "已收到消息:" + message;
clientSocket.Send (Encoding.UTF8.GetBytes (response));
Console.WriteLine ("已发送消息:" + response);
// 关闭客户端 Socket
clientSocket.Shutdown (SocketShutdown.Both);
clientSocket.Close ();
Console.WriteLine ("客户端已关闭连接");
}
}
}
```
客户端代码:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class Client {
public static void Main () {
// 建立客户端 Socket,连接到指定 IP 地址和端口号
Socket clientSocket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint (IPAddress.Parse ("127.0.0.1"), 8888);
clientSocket.Connect (ipEndPoint);
// 发送消息
string message = "Hello, Server!";
clientSocket.Send (Encoding.UTF8.GetBytes (message));
Console.WriteLine ("已发送消息:" + message);
// 接收消息
byte[] buffer = new byte[1024];
int count = clientSocket.Receive (buffer);
string response = Encoding.UTF8.GetString (buffer, 0, count);
Console.WriteLine ("服务端:" + response);
// 关闭客户端 Socket
clientSocket.Shutdown (SocketShutdown.Both);
clientSocket.Close ();
Console.WriteLine ("已关闭连接");
}
}
```
以上是一个基于 Socket 的简易聊天项目的示例代码,可以在本地环境中进行测试。当客户端连接到服务端后,客户端向服务端发送一条消息,服务端接收到消息后向客户端回复一条消息。如果您有任何其他的问题,欢迎随时向我提问。
阅读全文