当前位置: 首页 > 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、实现效果
在这里插入图片描述

相关文章:

  • 北京网站建设多少钱?
  • 辽宁网页制作哪家好_网站建设
  • 高端品牌网站建设_汉中网站制作
  • 哦吼,新模型?文生图领域的新模型FLUX.1(附模型下载网盘地址和详细使用方法)
  • onceperrequestfilter 不生效问题
  • Centos 安装 Gitlab
  • 数据库文件管理
  • hcip作业1
  • apex正则表达式匹配富文本字段内容,如何只匹配文本而忽略富文本符号
  • Astro 实现TodoList网页应用案例
  • 【机器学习基础】Scikit-learn主要用法
  • 【问题处理】海康视频websocket代理问题(websocket在业务系统https协议下调用海康ws协议)
  • 想提交BCSP小高组T4的同学请看这里~
  • 链接器找不到一些ACADO库中的函数定义,导致未定义引用的错误。
  • Leetcode 3143. 正方形中的最多点数(二分、数组字符串、位运算集合)
  • 函数function3
  • 解决Firefox代理身份验证弹出窗口问题:C#和Selenium实战指南
  • 量化金融人都在看哪些顶刊
  • 【跃迁之路】【641天】程序员高效学习方法论探索系列(实验阶段398-2018.11.14)...
  • Fastjson的基本使用方法大全
  • JS字符串转数字方法总结
  • Leetcode 27 Remove Element
  • Linux中的硬链接与软链接
  • Logstash 参考指南(目录)
  • unity如何实现一个固定宽度的orthagraphic相机
  • windows下使用nginx调试简介
  • 产品三维模型在线预览
  • 给第三方使用接口的 URL 签名实现
  • 面试题:给你个id,去拿到name,多叉树遍历
  • 前端js -- this指向总结。
  • 如何打造100亿SDK累计覆盖量的大数据系统
  • 实习面试笔记
  • 使用Swoole加速Laravel(正式环境中)
  • 项目实战-Api的解决方案
  • 小程序测试方案初探
  • 赢得Docker挑战最佳实践
  • scrapy中间件源码分析及常用中间件大全
  • ​决定德拉瓦州地区版图的关键历史事件
  • ​无人机石油管道巡检方案新亮点:灵活准确又高效
  • # 安徽锐锋科技IDMS系统简介
  • #数据结构 笔记三
  • #在 README.md 中生成项目目录结构
  • (160)时序收敛--->(10)时序收敛十
  • (6)STL算法之转换
  • (Redis使用系列) Springboot 使用redis的List数据结构实现简单的排队功能场景 九
  • (安卓)跳转应用市场APP详情页的方式
  • (笔记)M1使用hombrew安装qemu
  • (九十四)函数和二维数组
  • (每日持续更新)信息系统项目管理(第四版)(高级项目管理)考试重点整理 第13章 项目资源管理(七)
  • (七)MySQL是如何将LRU链表的使用性能优化到极致的?
  • (四)JPA - JQPL 实现增删改查
  • (一)utf8mb4_general_ci 和 utf8mb4_unicode_ci 适用排序和比较规则场景
  • (转)EOS中账户、钱包和密钥的关系
  • .gitignore文件---让git自动忽略指定文件
  • .htaccess 强制https 单独排除某个目录
  • .mkp勒索病毒解密方法|勒索病毒解决|勒索病毒恢复|数据库修复
  • .net MVC中使用angularJs刷新页面数据列表
  • .Net Redis的秒杀Dome和异步执行