C# TCP服务端代码 发送和接收数据 完成代码
时间: 2025-01-02 07:48:07 浏览: 23
在C#中,创建一个TCP服务器的基本步骤包括监听连接、接受客户端连接、发送和接收数据。以下是一个简单的示例代码片段,展示了如何创建一个基本的TCP服务端:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
public class TcpServer
{
private TcpListener server;
private const int Port = 8080; // 你想要的端口
public void Start()
{
try
{
server = new TcpListener(IPAddress.Any, Port);
server.Start();
Console.WriteLine($"TCP Server started on port {Port}");
while (true)
{
Console.WriteLine("Waiting for a connection...");
Socket client = server.AcceptSocket();
string dataReceived = ReceiveData(client);
Console.WriteLine($"Received from client: {dataReceived}");
SendData(client, "Hello, you've connected!");
client.Close();
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
private string ReceiveData(Socket socket)
{
byte[] buffer = new byte[1024];
int receivedBytes = socket.Receive(buffer);
if (receivedBytes > 0)
{
return Encoding.ASCII.GetString(buffer, 0, receivedBytes).Trim();
}
else
{
return "";
}
}
private void SendData(Socket socket, string message)
{
byte[] data = Encoding.ASCII.GetBytes(message);
socket.Send(data, 0, data.Length, SocketFlags.None);
}
}
// 要启动服务器,实例化并调用Start方法
public static void Main(string[] args)
{
var server = new TcpServer();
server.Start();
}
```
这个例子中,`Start()`方法启动了服务器,当有新连接到来时,它会接受连接,然后接收客户端发送的数据,并回应一条消息。注意这只是一个基础版本,实际应用中需要添加错误处理和更复杂的数据交互。
阅读全文