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);
    }
}

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

相关推荐
bicijinlian36 分钟前
.Net HttpClient 使用代理功能
c#·.net·httpclient·.net httpclient·httpclient 代理
敲代码的 蜡笔小新5 小时前
【行为型之中介者模式】游戏开发实战——Unity复杂系统协调与通信架构的核心秘诀
unity·设计模式·c#·中介者模式
程序猿多布6 小时前
使用Visual Studio将C#程序发布为.exe文件
c#·visual studio
别致的影分身6 小时前
websocketpp 安装及使用
websocket
老衲有点帅7 小时前
C#多线程Thread
开发语言·c#
界面开发小八哥7 小时前
界面控件DevExpress WinForms v24.2 - 数据处理功能增强
.net·界面控件·devexpress·ui开发·winforms
PascalMing8 小时前
C# 通过脚本实现接口
c#·codeanalysis·接口派生
敲代码的 蜡笔小新12 小时前
【行为型之观察者模式】游戏开发实战——Unity事件驱动架构的核心实现策略
观察者模式·unity·设计模式·c#
向宇it12 小时前
【unity游戏开发——编辑器扩展】使用EditorGUI的EditorGUILayout绘制工具类在自定义编辑器窗口绘制各种UI控件
开发语言·ui·unity·c#·编辑器·游戏引擎
FAREWELL0007518 小时前
Unity基础学习(九)输入系统全解析:鼠标、键盘与轴控制
学习·unity·c#·游戏引擎