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

C#用Socket实现TCP客户端

1、TCP客户端实现代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;namespace PtLib.TcpClient
{public delegate void TcpClientReceivedEventHandler(TcpClientStateEventArgs args);public class TcpClient{//接收委托public event TcpClientReceivedEventHandler TcpReceived;//private string _ip = "127.0.0.1";//private int _port = 8080;//Socket socket = null;//Thread thread = null;/// <summary>/// /// </summary>/// <param name="ip"></param>/// <param name="port"></param>public TcpClient(string ip,int port) { _ip = ip;_port = port;}/// <summary>/// /// </summary>public void Open(){socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPEndPoint endPoint=new IPEndPoint(IPAddress.Parse(_ip), _port);socket.Connect(endPoint);thread = new Thread(Receiver);thread.IsBackground = true;thread.Start();}private void Receiver(){while (true){byte[] buffer = new byte[1024*1024];int length = socket.Receive(buffer);if(length > 0){byte[] b = new byte[length];Buffer.BlockCopy(buffer, 0, b, 0, length);TcpClientStateEventArgs args = new TcpClientStateEventArgs();args.buffer = b;TcpReceived?.Invoke(args);}}}public void Send(byte[] data){socket.Send(data);}/// <summary>/// /// </summary>public void Close() {socket?.Close();thread?.Abort();socket = null;thread = null;}}/// <summary>/// Tcp状态事件参数类/// </summary>public class TcpClientStateEventArgs : EventArgs{public byte[] buffer = null;}
}

2、应用程序

using PtLib.TcpServer;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;namespace TcpClient
{public partial class Form1 : Form{PtLib.TcpClient.TcpClient tcpClient = null;/// <summary>/// /// </summary>public Form1(){InitializeComponent();}/// <summary>/// /// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btnConnect_Click(object sender, EventArgs e){if (btnConnect.Text.Equals("连接")){btnConnect.Text = "断开";string ip = tbClientIp.Text.Trim();int port = int.Parse(tbClientPort.Text.Trim());tcpClient = new PtLib.TcpClient.TcpClient(ip, port);tcpClient.Open();tcpClient.TcpReceived += TcpClient_TcpReceived;}else{btnConnect.Text = "连接";tcpClient.Close();}}private void TcpClient_TcpReceived(PtLib.TcpClient.TcpClientStateEventArgs args){string str = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:fff") + ":";str += Encoding.UTF8.GetString(args.buffer);this.Invoke(new Action(() =>{lbxReceive.Items.Add(str);}));}/// <summary>/// /// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btnSend_Click(object sender, EventArgs e){string str = tbxSend.Text.Trim();byte[] sendBytes = Encoding.UTF8.GetBytes(str);tcpClient.Send(sendBytes);}}
}

3、实现效果
在这里插入图片描述

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

相关文章:

  • jmeter-beanshell学习15-输入日期,计算前后几天的日期
  • Zabbix 7.0 安装
  • 软考高级-系统架构设计师
  • Notepad++ 安装 compare 插件
  • 大数据技术原理-spark的安装
  • 第四范式上线搜广推一体化平台 赋能企业高效增长
  • 智能小程序 Ray 开发面板 SDK —— 智能设备模型通用能力一键执行 SDK 汇总(一)
  • 特大喜讯:我的作品被河北某大学选做教材
  • 将时间用于符合当下的未来思考——读《纳瓦尔宝典》
  • CentOS-Stream-9仿冒Rocky-9通过Kolla-ansible部署OpenStack 2024.1
  • Python机器学习实战:分类算法之支持向量机-垃圾邮件识别
  • 秒懂Linux之自动化构建工具-make/Makefile
  • .net core + vue 搭建前后端分离的框架
  • 小阿轩yx-KVM+GFS 分布式存储系统构建 KVM 高可用
  • centos安装mysql 5.7版本
  • SQL——查询sql执行顺序
  • 钉耙编程(3)
  • python 线程池处理文件
  • AI技术和大模型对人才市场的影响
  • 解释“location”和“position”
  • Netty 必知必会(三)—— ByteBuf
  • 芋道以开源之名行下作之事 恬不知耻 标榜自己开源 公开源码+sql 不用再加入知识星球
  • wordpress中,wp_posts 文章的状态 有哪些,分别对应什么数值
  • 输入成绩问题(c语言)
  • 基于域名+基于ip+基于端口的虚拟主机+上线商务系统
  • vue每次路由跳转前将页面滚动到顶部
  • 【Qt】QDateTimeEdit
  • Redis和Mysql如何保持数据一致性
  • Java中Optional相关
  • AI在HR候选人关系管理中的革新应用