在WinForms中实现实时通讯,通常有以下几种方法:
System.Net.WebSockets
命名空间下的ClientWebSocket
类来实现WebSocket客户端。以下是一个简单的示例:using System;
using System.Net.WebSockets;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsWebSocketExample
{
public partial class MainForm : Form
{
private ClientWebSocket webSocket;
public MainForm()
{
InitializeComponent();
}
private async void btnConnect_Click(object sender, EventArgs e)
{
webSocket = new ClientWebSocket();
var uri = new Uri("ws://example.com/socket");
await webSocket.ConnectAsync(uri, CancellationToken.None);
MessageBox.Show("Connected!");
}
private async void btnSend_Click(object sender, EventArgs e)
{
if (webSocket != null && webSocket.State == WebSocketState.Open)
{
string message = txtMessage.Text;
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(message);
await webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None);
MessageBox.Show("Sent!");
}
else
{
MessageBox.Show("Not connected!");
}
}
private async void btnReceive_Click(object sender, EventArgs e)
{
if (webSocket != null && webSocket.State == WebSocketState.Open)
{
byte[] buffer = new byte[1024 * 4];
WebSocketReceiveResult result;
do
{
result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None);
string receivedMessage = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count);
MessageBox.Show("Received: " + receivedMessage);
} while (!result.CloseStatus.HasValue);
}
else
{
MessageBox.Show("Not connected!");
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (webSocket != null)
{
webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "Goodbye!", CancellationToken.None);
}
}
}
}
System.Net.Sockets
命名空间下的TcpListener
和TcpClient
类来实现TCP服务器和客户端。以下是一个简单的示例:服务器端:
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WinFormsTcpServerExample
{
public partial class MainForm : Form
{
private TcpListener server;
public MainForm()
{
InitializeComponent();
}
private async void btnStartServer_Click(object sender, EventArgs e)
{
server = new TcpListener(IPAddress.Any, 12345);
server.Start();
MessageBox.Show("Server started!");
while (true)
{
TcpClient client = await server.AcceptTcpClientAsync();
Task.Run(() => HandleClient(client));
}
}
private async void HandleClient(TcpClient client)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024 * 4];
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
MessageBox.Show("Received: " + receivedMessage);
string response = "Message received!";
byte[] responseBytes = Encoding.UTF8.GetBytes(response);
await stream.WriteAsync(responseBytes, 0, responseBytes.Length);
}
client.Close();
}
private void btnStopServer_Click(object sender, EventArgs e)
{
if (server != null)
{
server.Stop();
}
}
}
}
客户端:
using System;
using System.Net.Sockets;
using System.Text;
using System.Windows.Forms;
namespace WinFormsTcpClientExample
{
public partial class MainForm : Form
{
private TcpClient client;
public MainForm()
{
InitializeComponent();
}
private async void btnConnect_Click(object sender, EventArgs e)
{
client = new TcpClient("127.0.0.1", 12345);
MessageBox.Show("Connected!");
}
private async void btnSend_Click(object sender, EventArgs e)
{
if (client != null && client.Connected)
{
string message = txtMessage.Text;
byte[] buffer = Encoding.UTF8.GetBytes(message);
NetworkStream stream = client.GetStream();
await stream.WriteAsync(buffer, 0, buffer.Length);
MessageBox.Show("Sent!");
}
else
{
MessageBox.Show("Not connected!");
}
}
private async void btnReceive_Click(object sender, EventArgs e)
{
if (client != null && client.Connected)
{
NetworkStream stream = client.GetStream();
byte[] buffer = new byte[1024 * 4];
int bytesRead;
while ((bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length)) != 0)
{
string receivedMessage = Encoding.UTF8.GetString(buffer, 0, bytesRead);
MessageBox.Show("Received: " + receivedMessage);
}
}
else
{
MessageBox.Show("Not connected!");
}
}
private void btnDisconnect_Click(object sender, EventArgs e)
{
if (client != null)
{
client.Close();
}
}
}
}
选择哪种方法取决于您的需求和项目规模。WebSocket和TCP适用于实时通讯场景,而第三方库可能提供更多的功能和易用性。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。