在C# WinForms應用程序中實現網絡通信,可以使用多種方法。以下是一些常見的方法:
HttpClient
進行HTTP請求HttpClient
是.NET Core和.NET Framework中都有的類,可以用來發送HTTP請求和接收HTTP響應。
using System;
using System.Net.Http;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class MainForm : Form
{
private HttpClient client = new HttpClient();
public MainForm()
{
InitializeComponent();
}
private async void btnSendRequest_Click(object sender, EventArgs e)
{
string url = "https://api.example.com/data";
HttpResponseMessage response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
string data = await response.Content.ReadAsStringAsync();
MessageBox.Show(data);
}
else
{
MessageBox.Show($"Error: {response.StatusCode}");
}
}
}
TcpClient
進行TCP通信TcpClient
可以用來建立TCP連接并進行雙向通信。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class MainForm : Form
{
private TcpClient client;
private NetworkStream stream;
public MainForm()
{
InitializeComponent();
}
private async void btnConnect_Click(object sender, EventArgs e)
{
string server = "127.0.0.1";
int port = 5000;
client = new TcpClient(server, port);
stream = client.GetStream();
byte[] buffer = new byte[1024];
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
string receivedData = Encoding.UTF8.GetString(buffer, 0, bytesRead);
MessageBox.Show(receivedData);
string response = "Hello from client!";
byte[] sendData = Encoding.UTF8.GetBytes(response);
await stream.WriteAsync(sendData, 0, sendData.Length);
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (stream != null)
{
stream.Close();
stream = null;
}
if (client != null)
{
client.Close();
client = null;
}
}
}
UdpClient
進行UDP通信UdpClient
可以用來發送和接收UDP數據報。
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
public partial class MainForm : Form
{
private UdpClient udpClient;
public MainForm()
{
InitializeComponent();
}
private async void btnSendUDP_Click(object sender, EventArgs e)
{
string server = "127.0.0.1";
int port = 5001;
udpClient = new UdpClient();
IPAddress ipAddress = IPAddress.Parse(server);
IPEndPoint endPoint = new IPEndPoint(ipAddress, port);
string message = "Hello from client!";
byte[] sendData = Encoding.UTF8.GetBytes(message);
udpClient.Send(sendData, sendData.Length, endPoint);
byte[] receiveBuffer = new byte[1024];
int bytesReceived = udpClient.Receive(ref receiveBuffer);
string receivedData = Encoding.UTF8.GetString(receiveBuffer, 0, bytesReceived);
MessageBox.Show(receivedData);
}
private void btnStopUDP_Click(object sender, EventArgs e)
{
udpClient.Close();
}
}
WCF是一個強大的框架,可以用來創建、發布、消費和管理服務。
首先,定義一個WCF服務合同:
using System.ServiceModel;
[ServiceContract]
public interface IMyService
{
[OperationContract]
string GetData();
}
然后,實現WCF服務:
using System.ServiceModel;
public class MyService : IMyService
{
public string GetData()
{
return "Hello from service!";
}
}
接下來,配置服務并啟動服務:
using System.ServiceProcess;
public class MyServiceHost : ServiceBase
{
private ServiceHost serviceHost;
protected override void OnStart(string[] args)
{
if (serviceHost != null)
{
serviceHost.Close();
}
serviceHost = new ServiceHost(typeof(MyService), new Uri("net.pipe://localhost"));
serviceHost.AddServiceEndpoint(typeof(IMyService), new NetNamedPipeBinding(), "MyService");
serviceHost.Open();
}
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
}
最后,在WinForms客戶端中使用ChannelFactory
來調用服務:
using System;
using System.ServiceModel;
using System.Windows.Forms;
public partial class MainForm : Form
{
private IMyService myService;
public MainForm()
{
InitializeComponent();
}
private async void btnCallService_Click(object sender, EventArgs e)
{
using (var factory = new ChannelFactory<IMyService>(new NetNamedPipeBinding(), new EndpointAddress("net.pipe://localhost/MyService")))
{
myService = factory.CreateChannel();
string data = await myService.GetDataAsync();
MessageBox.Show(data);
}
}
}
這些方法可以根據具體需求選擇使用,以實現C# WinForms應用程序中的網絡通信。