C#winform编写服务器端和客户端, 用TCP IP 纯代码互相发送接受消息
时间: 2024-09-11 07:05:56 浏览: 74
在C#中使用WinForms编写基于TCP/IP的服务器端和客户端,需要使用到`System.Net`和`System.Net.Sockets`命名空间下的类。以下是一个简化的示例介绍如何实现这样的网络通信。
### 服务器端
服务器端需要监听特定的端口,等待客户端的连接请求,并建立连接之后发送或接收消息。服务器端的代码示例如下:
```csharp
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class TcpServer
{
private TcpListener tcpListener;
private bool listening;
public void Start(int port)
{
listening = true;
tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
Console.WriteLine("服务器启动,正在监听端口:" + port);
while (listening)
{
TcpClient client = tcpListener.AcceptTcpClient();
Console.WriteLine("客户端连接:" + client.Client.RemoteEndPoint);
Thread clientThread = new Thread(HandleClient);
clientThread.Start(client);
}
}
private void HandleClient(object obj)
{
TcpClient client = (TcpClient)obj;
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead;
try
{
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("接收到客户端消息:" + message);
// 回复客户端
string reply = "服务器回复:" + message;
byte[] data = Encoding.ASCII.GetBytes(reply);
stream.Write(data, 0, data.Length);
stream.Flush();
}
}
catch (Exception e)
{
Console.WriteLine("连接关闭:" + e.Message);
}
finally
{
stream.Close();
client.Close();
}
}
}
```
### 客户端
客户端需要连接到服务器的IP地址和端口,然后通过建立的连接发送消息或接收服务器端的消息。客户端的代码示例如下:
```csharp
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
public class TcpClientExample
{
private TcpClient client;
public void ConnectToServer(string ipAddress, int port)
{
client = new TcpClient();
client.Connect(ipAddress, port);
NetworkStream stream = client.GetStream();
Console.WriteLine("连接到服务器成功");
// 发送消息
string messageToSend = "你好,服务器!";
byte[] data = Encoding.ASCII.GetBytes(messageToSend);
stream.Write(data, 0, data.Length);
stream.Flush();
// 接收回复
byte[] buffer = new byte[1024];
int bytesRead = stream.Read(buffer, 0, buffer.Length);
string reply = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("从服务器接收到回复:" + reply);
stream.Close();
client.Close();
}
}
```
### 如何使用
1. 在服务器端创建`TcpServer`的实例,并调用`Start`方法开始监听端口。
2. 在客户端创建`TcpClientExample`的实例,并调用`ConnectToServer`方法连接到服务器。
###
阅读全文