c# socket通信代码
时间: 2024-10-16 20:01:16 浏览: 40
在 C# 中,Socket 通信通常用于网络应用程序,如客户端服务器模型。下面是一个简单的例子,展示了如何创建一个TCP服务器监听连接并处理客户端请求:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
class Server
{
static void Main()
{
TcpListener listener = new TcpListener(IPAddress.Any, 8080); // 创建监听任意IP地址的8080端口
listener.Start(); // 启动监听
Console.WriteLine("Server is listening on port 8080...");
while (true)
{
TcpClient client = listener.AcceptTcpClient(); // 接受新的客户端连接
Console.WriteLine($"Accepted connection from {client.Client.RemoteEndPoint}");
using (NetworkStream stream = client.GetStream())
{
byte[] buffer = new byte[1024];
int read;
while ((read = stream.Read(buffer, 0, buffer.Length)) > 0)
{
string message = System.Text.Encoding.ASCII.GetString(buffer, 0, read);
Console.WriteLine($"Received message: {message}");
// 这里你可以编写发送回复的逻辑
// 例如,向客户端回显消息
byte[] reply = Encoding.ASCII.GetBytes(message + " Server received!");
stream.Write(reply, 0, reply.Length);
}
}
client.Close();
}
}
}
阅读全文