当前位置: 首页 > news >正文

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

一、新建WinForm Socket服务端程序

注:rtbReceviceMsg为RichTextBox控件

服务端程序、界面

在这里插入图片描述
在这里插入图片描述

服务端代码

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客户端程序

客户端程序、界面

在这里插入图片描述
在这里插入图片描述

客户端代码

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

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

在这里插入图片描述

http://www.lryc.cn/news/437442.html

相关文章:

  • Kamailio-基于Homer与heplify的SIP信令监控-2
  • unity3d入门教程四
  • 无人机飞控的原理!!!
  • 深入解析代理模式:静态代理、JDK 动态代理和 CGLIB 的全方位对比!
  • 51单片机快速入门之独立按键
  • 设计模式之工厂模式(通俗易懂--代码辅助理解【Java版】)
  • 速盾:高防 cdn 分布式防御攻击?
  • Unity3D类似于桌面精灵的功能实现
  • Audio Over IP的PTP时钟初探
  • 【加密社】深入理解TON智能合约 (FunC语法)
  • 笔试强训day11
  • 移动应用开发与测试赛题
  • Qt常用控件——QLineEdit
  • (postman)接口测试进阶实战
  • R语言统计分析——功效分析(比例、卡方检验)
  • Leetcode 每日一题:Longest Increasing Path in a Matrix
  • ARCGIS PRO DSK MapTool
  • 国网B接口 USC安防平台 海康摄像机配置
  • Win10安装.net FrameWork3.5失败解决方法
  • 【pipenv】—— 虚拟环境管理工具近乎全面的总结
  • windows C++-并行编程-并行算法(五) -选择排序算法
  • 【系统架构设计师-2014年真题】案例分析-答案及详解
  • windows C++-并行编程-并行算法(三)-分区工作
  • 下载 llama2-7b-hf 全流程【小白踩坑记录】
  • Codeforces practice C++ 2024/9/11 - 2024/9/13
  • RabbitMQ创建交换机和队列——配置类 注解
  • proteus+51单片机+AD/DA学习5
  • 【Python机器学习】长短期记忆网络(LSTM)
  • 【Go】使用Goland创建第一个Go项目
  • STM32学习笔记(一、使用DAP仿真器下载程序)