在C# WinForm中實現網絡通信,可以使用.NET框架提供的System.Net.Sockets
命名空間中的類。以下是一個簡單的TCP客戶端和服務器端的示例。
首先,創建一個服務器端應用程序:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
namespace ServerApp
{
public partial class Form1 : Form
{
private TcpListener _listener;
private Thread _acceptThread;
public Form1()
{
InitializeComponent();
StartServer();
}
private void StartServer()
{
_listener = new TcpListener(IPAddress.Any, 8000);
_listener.Start();
_acceptThread = new Thread(AcceptClients);
_acceptThread.Start();
}
private void AcceptClients()
{
while (true)
{
TcpClient client = _listener.AcceptTcpClient();
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;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
Invoke((MethodInvoker)delegate { textBoxMessages.AppendText($"Received: {message}{Environment.NewLine}"); });
}
client.Close();
}
}
}
接下來,創建一個客戶端應用程序:
using System;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace ClientApp
{
public partial class Form1 : Form
{
private TcpClient _client;
private NetworkStream _stream;
public Form1()
{
InitializeComponent();
ConnectToServer();
}
private void ConnectToServer()
{
_client = new TcpClient("127.0.0.1", 8000);
_stream = _client.GetStream();
}
private void buttonSend_Click(object sender, EventArgs e)
{
string message = textBoxMessage.Text;
byte[] buffer = Encoding.UTF8.GetBytes(message);
_stream.Write(buffer, 0, buffer.Length);
textBoxMessage.Clear();
}
}
}
這個示例中,服務器端監聽8000端口,接受客戶端連接,并在收到消息時將其顯示在文本框中。客戶端連接到服務器后,可以通過點擊“發送”按鈕發送消息。
請注意,這只是一個簡單的示例,實際應用中可能需要考慮更多的錯誤處理和功能。