Winform中如何实现实时通讯

发布时间:2024-12-17 20:43:17 作者:小樊
来源:亿速云 阅读:82

在WinForms中实现实时通讯,通常有以下几种方法:

  1. 使用WebSocket:WebSocket是一种在单个TCP连接上进行全双工通信的协议。在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);
            }
        }
    }
}
  1. 使用TcpListener和TcpClient:TCP(传输控制协议)是一种面向连接的、可靠的、基于字节流的传输层通信协议。可以使用System.Net.Sockets命名空间下的TcpListenerTcpClient类来实现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();
            }
        }
    }
}
  1. 使用第三方库:有许多第三方库可以帮助您在WinForms中实现实时通讯,例如SignalR、Xamarin.Essentials等。这些库通常提供了更高级的功能和更好的性能,但可能需要额外的学习和配置。

选择哪种方法取决于您的需求和项目规模。WebSocket和TCP适用于实时通讯场景,而第三方库可能提供更多的功能和易用性。

推荐阅读:
  1. thinkphp中的fetch方法如何用
  2. thinkphp中where方法如何用

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

上一篇:怎样优化Winform网络传输

下一篇:C# Winform怎样处理复杂数据

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》