WPF基本的客户端和服务端通信代码
时间: 2023-10-30 22:07:25 浏览: 95
WPF 中的客户端和服务端通信可以使用多种方式实现,包括但不限于:
1. 使用 Socket 进行通信
客户端代码示例:
```csharp
using System.Net.Sockets;
private void ConnectToServer(string serverIP, int serverPort)
{
Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
clientSocket.Connect(serverIP, serverPort);
// 发送数据
byte[] data = Encoding.UTF8.GetBytes("Hello, server!");
clientSocket.Send(data);
// 接收数据
byte[] buffer = new byte[1024];
int count = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, count);
MessageBox.Show(message);
// 关闭连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
```
服务端代码示例:
```csharp
using System.Net;
using System.Net.Sockets;
private void StartServer(int port)
{
Socket serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
serverSocket.Bind(new IPEndPoint(IPAddress.Any, port));
serverSocket.Listen(10);
while (true)
{
Socket clientSocket = serverSocket.Accept();
// 接收数据
byte[] buffer = new byte[1024];
int count = clientSocket.Receive(buffer);
string message = Encoding.UTF8.GetString(buffer, 0, count);
MessageBox.Show(message);
// 发送数据
byte[] data = Encoding.UTF8.GetBytes("Hello, client!");
clientSocket.Send(data);
// 关闭连接
clientSocket.Shutdown(SocketShutdown.Both);
clientSocket.Close();
}
}
```
2. 使用 WCF 进行通信
客户端代码示例:
```csharp
using System.ServiceModel;
private void ConnectToServer(string serverIP, int serverPort)
{
EndpointAddress endpoint = new EndpointAddress($"net.tcp://{serverIP}:{serverPort}/MyService");
NetTcpBinding binding = new NetTcpBinding();
using (MyServiceClient client = new MyServiceClient(binding, endpoint))
{
// 调用服务端方法
string message = client.SayHello("Hello, server!");
MessageBox.Show(message);
}
}
```
服务端代码示例:
```csharp
using System.ServiceModel;
[ServiceContract]
public interface IMyService
{
[OperationContract]
string SayHello(string message);
}
public class MyService : IMyService
{
public string SayHello(string message)
{
MessageBox.Show(message);
return "Hello, client!";
}
}
private void StartServer(int port)
{
ServiceHost host = new ServiceHost(typeof(MyService));
host.AddServiceEndpoint(typeof(IMyService), new NetTcpBinding(), $"net.tcp://localhost:{port}/MyService");
host.Open();
}
```
以上示例仅供参考,具体实现方式需要根据实际需求进行调整。
阅读全文