C# tcp 服务器发送字符串给客户端
时间: 2024-09-28 16:15:35 浏览: 64
在C#中创建TCP服务器并发送字符串给客户端,通常需要使用`System.Net.Sockets`命名空间下的`TcpListener`和`Socket`类。以下是简化的示例步骤:
```csharp
using System;
using System.Net;
using System.IO;
class Server
{
private TcpListener server;
private const int PORT = 8080; // 设置端口
public void StartServer()
{
try
{
server = new TcpListener(IPAddress.Any, PORT);
server.Start();
Console.WriteLine($"Server started on port {PORT}...");
while (true)
{
TcpClient client = server.AcceptTcpClient(); // 等待客户端连接
using (NetworkStream stream = client.GetStream())
{
StreamReader reader = new StreamReader(stream);
StreamWriter writer = new StreamWriter(stream);
string messageToSend = "Hello from the server!"; // 要发送的字符串
writer.WriteLine(messageToSend); // 写入数据
writer.Flush(); // 清空缓存
Console.WriteLine($"Sent message: {messageToSend}");
// 接收客户端的回应
string response = reader.ReadLine();
Console.WriteLine($"Received response: {response}");
}
}
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
}
}
static void Main(string[] args)
{
Server serverInstance = new Server();
serverInstance.StartServer();
}
}
```
在这个例子中,服务器会一直等待新客户端连接,并向每个连接的客户端发送预设的消息。当客户端回复后,服务器会读取并打印回音。
阅读全文