C# 使用Socket通信,新建WinForm服务端、客户端程序

一、新建WinForm Socket服务端程序

注:rtbReceviceMsg为RichTextBox控件

服务端程序、界面


服务端代码

csharp 复制代码
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    public virtual void TriggerOnUpdateUI(string message)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new Action<string>(TriggerOnUpdateUI), message);
        }
        else
        {
            rtbReceviceMsg.Text += message + "\n";
        }
    }
    private void btnStartServer_Click(object sender, EventArgs e)
    {
        TcpServer.StartListening(9999, this);
        btnStartServer.Enabled = false;
    }

    private void btnStopServer_Click(object sender, EventArgs e)
    {
        TcpServer.StopListening();
        btnStartServer.Enabled = true;
    }
}
 public class TcpServer
 {
     public static Form1 _mainForm;
     private static TcpListener _listener;
     private static bool _isRunning;
     public static void StartListening(int port, Form1 form)
     {
         _mainForm = form;
         _listener = new TcpListener(IPAddress.Loopback, port);
         _listener.Start();
         _isRunning=true;
         Console.WriteLine("Server listening on port " + port);

         Task.Run(() => ListenForClients());
     }
     public static void ListenForClients()
     {
         while (_isRunning)
         {
             try
             {
                 TcpClient client = _listener.AcceptTcpClient();
                 Console.WriteLine("Client connected");
                 HandleClient(client);
             }
             catch (SocketException)
             {
                 if (!_isRunning)
                 {
                     break;
                 }
             }
         }
     }
     private static void HandleClient(TcpClient client)
     {
         NetworkStream stream = client.GetStream();
         byte[] buffer = new byte[1024];
         int bytesRead;
         while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
         {
             string message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
             Console.WriteLine("received" + message);
             stream.Write(buffer, 0, bytesRead);

             _mainForm.BeginInvoke(new Action(() => _mainForm.TriggerOnUpdateUI(message)));
         }
     }
     public static void StopListening()
     {
         _isRunning = false;
         _listener?.Stop();
     }
 }

二、新建WinForm Socket客户端程序

客户端程序、界面


客户端代码

csharp 复制代码
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    public static void ConnectToServer(string hostname, int port)
    {
        try
        {
            using (TcpClient tcpClient = new TcpClient(hostname, port))
            {
                Console.WriteLine("Connected to server");

                NetworkStream stream = tcpClient.GetStream();

                byte[] data = Encoding.ASCII.GetBytes($"Hellow,Server!{DateTime.Now.ToString()}");
                stream.Write(data, 0, data.Length);
                Console.WriteLine("Sent:Hellow,Server!");

                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                string response = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"Response: {response}");
            }
        }
        catch (SocketException ex)
        {
            MessageBox.Show($"连接异常:{ex.Message}");
        }
    }
    private void btnStartServer_Click(object sender, EventArgs e)
    {
        ConnectToServer("127.0.0.1", 9999);
    }
}

服务端、客户端程序运行效果

相关推荐
△曉風殘月〆4 小时前
WPF MVVM入门系列教程(二、依赖属性)
c#·wpf·mvvm
逐·風6 小时前
unity关于自定义渲染、内存管理、性能调优、复杂物理模拟、并行计算以及插件开发
前端·unity·c#
m0_656974749 小时前
C#中的集合类及其使用
开发语言·c#
九鼎科技-Leo9 小时前
了解 .NET 运行时与 .NET 框架:基础概念与相互关系
windows·c#·.net
九鼎科技-Leo11 小时前
什么是 ASP.NET Core?与 ASP.NET MVC 有什么区别?
windows·后端·c#·asp.net·mvc·.net
.net开发11 小时前
WPF怎么通过RestSharp向后端发请求
前端·c#·.net·wpf
小乖兽技术11 小时前
C#与C++交互开发系列(二十):跨进程通信之共享内存(Shared Memory)
c++·c#·交互·ipc
幼儿园园霸柒柒12 小时前
第七章: 7.3求一个3*3的整型矩阵对角线元素之和
c语言·c++·算法·矩阵·c#·1024程序员节
平凡シンプル14 小时前
C# EF 使用
c#
丁德双15 小时前
winform 加载 office excel 插入QRCode图片如何设定位置
c#·excel