網(wǎng)站首頁 編程語言 正文
本文實例為大家分享了C#基于Sockets類實現(xiàn)TCP通訊的具體代碼,供大家參考,具體內(nèi)容如下
最終效果
TCPClient
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using System.Net.Sockets; using System.Threading; namespace TCPClient02 { ? ? public partial class Form1 : Form ? ? { ? ? ? ? public Form1() ? ? ? ? { ? ? ? ? ? ? InitializeComponent(); ? ? ? ? } ? ? ? ? Socket socketSend; ? ? ? ? private void button1_Click(object sender, EventArgs e) ? ? ? ? { ? ? ? ? ? ? //Create socket ? ? ? ? ? ? socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ? ? ? ? ? ? IPAddress ip = IPAddress.Parse(textBox1.Text); ? ? ? ? ? ? IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text)); ? ? ? ? ? ? IDInfo idinfo = new IDInfo(); ?//Read ID number information ? ? ? ? ? ? //Get the IP address and port number of the remote server ? ? ? ? ? ? socketSend.Connect(point); ? ? ? ? ? ? ShowMessages("Connection succeeded"); ? ? ? ? ? ? //Start a new thread and keep receiving messages sent by the server ? ? ? ? ? ? Thread th = new Thread(ReciveMessages); ? ? ? ? ? ? th.IsBackground = true; ? ? ? ? ? ? th.Start(); ? ? ? ? } ? ? ? ? private void button2_Click(object sender, EventArgs e) ? ? ? ? { ? ? ? ? ? ? string str = textBox3.Text.Trim(); ? ? ? ? ? ? byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); ? ? ? ? ? ? socketSend.Send(buffer); ? ? ? ? } ? ? ? ? void ShowMessages(string str) ? ? ? ? { ? ? ? ? ? ? textBox4.AppendText(str + "\r\n"); ? ? ? ? } ? ? ? ? void ReciveMessages() ? ? ? ? { ? ? ? ? ? ? while (true) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? byte[] buffer = new byte[1024 * 1024 * 3]; ? ? ? ? ? ? ? ? int r = socketSend.Receive(buffer); ? ? ? ? ? ? ? ? if (r == 0) ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? string s = Encoding.UTF8.GetString(buffer, 0, r); ? ? ? ? ? ? ? ? ShowMessages(socketSend.RemoteEndPoint + ":" + s); ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? private void Form1_Load(object sender, EventArgs e) ? ? ? ? { ? ? ? ? ? ? Control.CheckForIllegalCrossThreadCalls = false; ? ? ? ? } ? ? } }
TCPserver
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Net; using System.Threading; namespace TCPserver { ? ? public partial class Form1 : Form ? ? { ? ? ? ? public Form1() ? ? ? ? { ? ? ? ? ? ? InitializeComponent(); ? ? ? ? } ? ? ? ? private void button1_Click(object sender, EventArgs e) ? ? ? ? { ? ? ? ? ? ? try ? ? ? ? ? ? { ? ? ? ? ? ? ? ? //創(chuàng)建一個負責監(jiān)聽的Socket ? ? ? ? ? ? ? ? Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ? ? ? ? ? ? ? ? //創(chuàng)建ip地址和端口號 ? ? ? ? ? ? ? ? //IPAddress ip = IPAddress.Parse(textBox1.Text); ? ? ? ? ? ? ? ? IPAddress ip = IPAddress.Any; ? ? ? ? ? ? ? ? IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text)); ? ? ? ? ? ? ? ? //讓負責監(jiān)聽的socket綁定ip地址和端口號 ? ? ? ? ? ? ? ? socketWatch.Bind(point); ? ? ? ? ? ? ? ? ShowMsg("監(jiān)聽成功"); ? ? ? ? ? ? ? ? //設置監(jiān)聽隊列(某一時刻連接客戶端的最大數(shù)目) ? ? ? ? ? ? ? ? socketWatch.Listen(10); ? ? ? ? ? ? ? ? //線程執(zhí)行的方法 ? ? ? ? ? ? ? ? Thread th = new Thread(Listen); ? //服務器開始監(jiān)聽 ? ? ? ? ? ? ? ? th.IsBackground = true; ? ? ? ? ? ? ? ? th.Start(socketWatch); ? ? ? ? ? ? } ? ? ? ? ? ? catch ? ? ? ? ? ? { ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? void ShowMsg(string str) ? ? ? ? { ? ? ? ? ? ? textBox3.AppendText(str + "\r\n"); ? ? ? ? } ? ? ? ? /// <summary> ? ? ? ? /// 等待客戶端的連接 并且創(chuàng)建與之通信的Socket ? ? ? ? /// </summary> ? ? ? ? ///? ? ? ? ? Socket socketSend; ? ? ? ? void Listen(object o) ? ? ? ? { ? ? ? ? ? ? Socket socketWatch = o as Socket; ? ? ? ? ? ? //負責監(jiān)聽的socket 來接收客戶端的連接 ? ? ? ? ? ? ? //創(chuàng)建跟客戶端通信的socket ? ? ? ? ? ? while (true) ? ? ? ? ? ? { ? ? ? ? ? ? ? ? try ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? socketSend = socketWatch.Accept(); ? ? ? ? ? ? ? ? ? ? ShowMsg(socketSend.RemoteEndPoint.ToString() + "連接成功"); ? ? ? ? ? ? ? ? ? ? //開始一個新的線程不斷接受客戶端發(fā)送過來的消息 ? ? ? ? ? ? ? ? ? ? Thread th = new Thread(Recive); ? ? ? ? ? ? ? ? ? ? th.IsBackground = true; ? ? ? ? ? ? ? ? ? ? th.Start(socketSend); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? catch ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? } ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? /// <summary> ? ? ? ? /// 服務器不斷接受客戶端發(fā)送過來的消息 ? ? ? ? /// </summary> ? ? ? ? /// <param name="o"></param> ? ? ? ? void Recive(object o) ? ? ? ? { ? ? ? ? ? ?? ? ? ? ? ? ? Socket socketSend = o as Socket; ? ? ? ? ? ? while (true) ? ? ? ? ? ? { ? ? ? ? ? ? ? ?try ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? //客戶端連接成功后,服務器應該接收客戶端發(fā)來的消息 ? ? ? ? ? ? ? ? ? ? byte[] buffer = new byte[1024 * 1024 * 2]; ? ? ? ? ? ? ? ? ? ? //實際接收到的有效字節(jié)數(shù) ? ? ? ? ? ? ? ? ? ? int bytelen = socketSend.Receive(buffer); ? ? ? ? ? ? ? ? ? ? if (bytelen == 0) ? ? ? ? ? ? ? ? ? ? { ? ? ? ? ? ? ? ? ? ? ? ? break; ? ? ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? ? ? string str = Encoding.UTF8.GetString(buffer, 0, bytelen); ? ? ? ? ? ? ? ? ? ? ShowMsg(socketSend.RemoteEndPoint + ":" + str); ? ? ? ? ? ? ? ? } ? ? ? ? ? ? ? ? catch ? ? ? ? ? ? ? ? { ?} ? ? ? ? ? ? ? ?? ? ? ? ? ? ? ? ?? ? ? ? ? ? ? } ? ? ? ? } ? ? ? ? private void textBox1_TextChanged(object sender, EventArgs e) ? ? ? ? { ? ? ? ? } ? ? ? ? private void Form1_Load(object sender, EventArgs e) ? ? ? ? { ? ? ? ? ? ? Control.CheckForIllegalCrossThreadCalls = false; ? ? ? ? } ? ? ? ?/// <summary> ? ? ? ?/// 服務器給客戶端發(fā)送消息 ? ? ? ?/// </summary> ? ? ? ?/// <param name="sender"></param> ? ? ? ?/// <param name="e"></param> ? ? ? ? private void button3_Click(object sender, EventArgs e) ? ? ? ? { ? ? ? ? ? ? string str = textBox4.Text; ? ? ? ? ? ? byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str); ? ? ? ? ? ? socketSend.Send(buffer); ? ? ? ? } ? ? } }
原文鏈接:https://blog.csdn.net/qq_43069920/article/details/119509295
相關推薦
- 2022-07-02 一個Python優(yōu)雅的數(shù)據(jù)分塊方法詳解_python
- 2022-05-05 輕量級ORM框架Dapper應用之返回多個結果集_實用技巧
- 2022-10-10 ASP.NET?MVC使用jQuery?ui的progressbar實現(xiàn)進度條_實用技巧
- 2022-12-03 FFmpeg?Principle學習new_video_stream添加視頻輸出流_Android
- 2022-06-02 Android?實例代碼帶你掌握FrameLayout_Android
- 2022-07-04 .NET性能優(yōu)化之為結構體數(shù)組使用StructLinq的問題解析_實用技巧
- 2023-01-15 GoLang內(nèi)存泄漏原因排查詳解_Golang
- 2022-11-10 Android使用popupWindow仿微信彈出框使用方法_Android
- 最近更新
-
- window11 系統(tǒng)安裝 yarn
- 超詳細win安裝深度學習環(huán)境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區(qū)別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優(yōu)雅實現(xiàn)加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發(fā)現(xiàn)-Nac
- Spring Security之基于HttpR
- Redis 底層數(shù)據(jù)結構-簡單動態(tài)字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發(fā)送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支