温馨提示×

c# winform的网络通信实现

c#
小樊
91
2024-09-02 04:37:34
栏目: 编程语言

在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端口,接受客户端连接,并在收到消息时将其显示在文本框中。客户端连接到服务器后,可以通过点击“发送”按钮发送消息。

请注意,这只是一个简单的示例,实际应用中可能需要考虑更多的错误处理和功能。

0