C#创建TCP Server
时间: 2024-10-17 21:05:06 浏览: 23
在C#中创建一个简单的TCP服务器,你可以使用System.Net套接字编程。以下是一个基础的步骤:
1. 引入必要的命名空间:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
```
2. 创建服务器端口和一个Socket对象:
```csharp
int port = 8080; // 指定监听的端口号
TcpListener listener = new TcpListener(IPAddress.Any, port);
```
3. 开始监听连接:
```csharp
listener.Start();
Console.WriteLine($"TCP服务器已启动,监听端口 {port} ...");
```
4. 接受客户端连接并处理请求:
```csharp
while (true)
{
Socket clientSocket = listener.AcceptSocket(); // 等待客户端连接
Console.WriteLine($"新连接来自: {clientSocket.RemoteEndPoint.ToString()}");
using (NetworkStream stream = clientSocket.GetStream())
{
byte[] buffer = new byte[1024];
int receivedBytes;
while ((receivedBytes = stream.Read(buffer, 0, buffer.Length)) > 0)
{
string data = Encoding.ASCII.GetString(buffer, 0, receivedBytes);
Console.WriteLine($"收到数据: {data}");
// 发送响应到客户端
string response = "Hello from server!";
byte[] responseBytes = Encoding.ASCII.GetBytes(response);
stream.Write(responseBytes, 0, responseBytes.Length);
// 如果需要关闭连接,在这里添加相应逻辑
}
}
}
```
5. 关闭监听器:
```csharp
// 当不再需要服务时,关闭监听器
listener.Stop();
```
阅读全文