Socket编程详解(一)服务端与客户端的双向对话

目录

预备知识

视频教程

项目前准备知识点

1、服务器端程序的编写步骤

2、客户端程序编写步骤

代码部分 

      1、服务端FrmServer.cs文件

        2、客户端FrmClient.cs文件

        3、启动文件Program.cs

结果展示 


预备知识

请查阅博客http://t.csdnimg.cn/jE4Tp

视频教程

链接:https://pan.baidu.com/s/13fkwlppoP9aYcXHiFEbKGQ?pwd=cvzn 
提取码:cvzn

项目前准备知识点


1、服务器端程序的编写步骤

第一步:调用socket()函数创建一个用于通信的套接字。

第二步:给已经创建的套接字绑定一个端口号,这一般通过设置网络套接口地址和调用bind()函数来实现。
第三步:调用listen()函数使套接字成为一个监听套接字。
第四步:调用accept()函数来接受客户端的连接,这是就可以和客户端通信了。
第五步:处理客户端的连接请求

第六步:终止连接。

 



2、客户端程序编写步骤

第一步:调用socket()函数创建一个用于通信的套接字。

第二步:通过设置套接字地址结构,说明客户端与之通信的服务器的IP地址和端口号。
第三步:调用connect()函数来建立与服务器的连接。
第四步:调用读写函数发送或者接收数据。
第五步:终止连接。

 

代码部分 

      1、服务端FrmServer.cs文件

        FrmServer.cs窗体

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;namespace SocketTCP
{//声明委托delegate void AddOnLineDelegate(string str, bool bl);//声明委托delegate void RecMsgDelegate(string str);public partial class FrmTCPServer : Form{public FrmTCPServer(){InitializeComponent();myAddOnline = AddOnline;myRcvMsg = RecMsg;myFileSave = FileSave;}//创建套接字Socket sock = null;//创建负责监听客户端连接的线程Thread threadListen = null;//创建URL与Socket的字典集合Dictionary<string, Socket> DicSocket = new Dictionary<string, Socket>();AddOnLineDelegate myAddOnline;RecMsgDelegate myRcvMsg;FileSaveDelegate myFileSave;#region 开始监听/// <summary>/// 开始监听/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_StartServer_Click(object sender, EventArgs e){//创建负责监听的套接字,注意其中参数:IPV4 字节流 TCPsock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);IPAddress address = IPAddress.Parse(this.txt_IP.Text.Trim());//根据IPAddress以及端口号创建IPE对象IPEndPoint endpoint = new IPEndPoint(address, int.Parse(this.txt_Port.Text.Trim()));try{sock.Bind(endpoint);Invoke(myRcvMsg, "服务器开启成功!");MessageBox.Show("开启服务成功!", "打开服务");}catch (Exception ex){MessageBox.Show("开启服务失败" + ex.Message, "打开服务");return;}sock.Listen(10);threadListen = new Thread(ListenConnecting);threadListen.IsBackground = true;threadListen.Start();this.btn_StartServer.Enabled = false;}#endregion#region 监听线程/// <summary>/// 监听线程/// </summary>private void ListenConnecting(){while (true){//一旦监听到一个客户端的连接,将会创建一个与该客户端连接的套接字Socket sockClient = sock.Accept();string client = sockClient.RemoteEndPoint.ToString();DicSocket.Add(client, sockClient);Invoke(myAddOnline, client, true);Invoke(myRcvMsg, client + "上线了!");//开启接受线程Thread thr = new Thread(ReceiveMsg);thr.IsBackground = true;thr.Start(sockClient);}}#endregion#region 接收线程/// <summary>/// 接收线程/// </summary>/// <param name="sockClient"></param>private void ReceiveMsg(object sockClient){Socket sckclient = sockClient as Socket;while (true){//定义一个2M缓冲区byte[] arrMsgRec = new byte[1024 * 1024 * 2];int length = -1;try{length = sckclient.Receive(arrMsgRec);}catch (Exception){string str = sckclient.RemoteEndPoint.ToString();Invoke(myRcvMsg, str + "下线了!");//从列表中移除URLInvoke(myAddOnline, str, false);DicSocket.Remove(str);break;}if (length == 0){string str = sckclient.RemoteEndPoint.ToString();Invoke(myRcvMsg, str + "下线了!");//从列表中移除URLInvoke(myAddOnline, str, false);DicSocket.Remove(str);break;}else{if (arrMsgRec[0] == 0){string strMsg = Encoding.UTF8.GetString(arrMsgRec, 1, length-1);string Msg = "[接收]     " + sckclient.RemoteEndPoint.ToString() + "     " + strMsg;Invoke(myRcvMsg, Msg);}if (arrMsgRec[0] == 1){Invoke(myFileSave, arrMsgRec,length);}}}}#endregion#region 委托方法体private void AddOnline(string url, bool bl){if (bl){this.lbOnline.Items.Add(url);}else{this.lbOnline.Items.Remove(url);}}private void RecMsg(string str){this.txt_Rcv.AppendText(str + Environment.NewLine);}private void FileSave(byte[] bt, int length){try{SaveFileDialog sfd = new SaveFileDialog();sfd.Filter = "word files(*.docx)|*.docx|txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|All files(*.*)|*.*";if (sfd.ShowDialog() == DialogResult.OK){string fileSavePath = sfd.FileName;using (FileStream fs = new FileStream(fileSavePath, FileMode.Create)){fs.Write(bt, 1, length - 1);Invoke(new Action(() => this.txt_Rcv.AppendText("[保存]     保存文件成功" + fileSavePath + Environment.NewLine)));}}}catch (Exception ex){MessageBox.Show("保存异常" + ex.Message, "保存文件出现异常");}}#endregion#region 发送消息/// <summary>/// 发送消息/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_SendToSingle_Click(object sender, EventArgs e){string StrMsg = this.txt_Send.Text.Trim();byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);byte[] arrSend = new byte[arrMsg.Length + 1];arrSend[0] = 0;Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);if (this.lbOnline.SelectedItems.Count == 0){MessageBox.Show("请选择你要发送的对象!", "发送提示");return;}else{foreach (string item in this.lbOnline.SelectedItems){DicSocket[item].Send(arrSend);string Msg = "[发送]     " + item + "     " + StrMsg;Invoke(myRcvMsg, Msg);}}}#endregion#region 群发消息/// <summary>/// 群发消息/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_SendToAll_Click(object sender, EventArgs e){string StrMsg = this.txt_Send.Text.Trim();byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);byte[] arrSend = new byte[arrMsg.Length + 1];arrSend[0] = 0;Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);foreach (string item in this.DicSocket.Keys){DicSocket[item].Send(arrSend);string Msg = "[发送]     " + item + "     " + StrMsg;Invoke(myRcvMsg, Msg);}Invoke(myRcvMsg, "[群发]     群发完毕!");}#endregion#region 打开客户端/// <summary>/// 打开客户端/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_Client_Click(object sender, EventArgs e){FrmTCPClient objFrm = new FrmTCPClient();objFrm.Show();}#endregion#region 选择文件/// <summary>/// 选择文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_SelectFile_Click(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.InitialDirectory = "D:\\";if (ofd.ShowDialog() == DialogResult.OK){this.txt_SelectFile.Text = ofd.FileName;}}#endregion#region 发送文件/// <summary>/// 发送文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_SendFile_Click(object sender, EventArgs e){if (string.IsNullOrEmpty(txt_SelectFile.Text)){MessageBox.Show("请选择您要发送的文件!", "发送文件提示");return;}string online = this.lbOnline.Text.Trim();if (string.IsNullOrEmpty(online)){MessageBox.Show("请选择您要发送的对象!", "发送文件提示");return;}using (FileStream fs = new FileStream(txt_SelectFile.Text, FileMode.Open)){string filename = Path.GetFileName(txt_SelectFile.Text);string StrMsg = "发送文件为:" + filename;byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);byte[] arrSend= new byte[arrMsg.Length + 1];arrSend[0] =0;Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);DicSocket[online].Send(arrSend);byte[] arrfileSend = new byte[1024 * 1024 * 2];int length = fs.Read(arrfileSend, 0, arrfileSend.Length);byte[] arrfile = new byte[length + 1];arrfile[0] = 1;Buffer.BlockCopy(arrfileSend, 0, arrfile, 1, length);DicSocket[online].Send(arrfile);}}#endregion}
}

        2、客户端FrmClient.cs文件

           FrmClient.cs窗体

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;namespace SocketTCP
{delegate void FileSaveDelegate(byte[] bt,int length);public partial class FrmTCPClient : Form{public FrmTCPClient(){InitializeComponent();MyFileSave = FileSave;}//Socket对象Socket sockClient = null;//接收线程Thread thrClient = null;//运行标志位private bool IsRunning = true;//文件保存委托对象FileSaveDelegate MyFileSave;#region 连接服务器/// <summary>/// 连接服务器/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_Connect_Click(object sender, EventArgs e){IPAddress address = IPAddress.Parse(this.txt_IP.Text.Trim());IPEndPoint Ipe = new IPEndPoint(address, int.Parse(this.txt_Port.Text.Trim()));sockClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);try{this.txt_Rcv.AppendText("与服务器连接中......" + Environment.NewLine);sockClient.Connect(Ipe);}catch (Exception ex){MessageBox.Show("连接失败" + ex.Message, "建立连接");return;}this.txt_Rcv.AppendText("与服务器连接成功" + Environment.NewLine);this.btn_Connect.Enabled = false;thrClient = new Thread(ReceiceMsg);thrClient.IsBackground = true;thrClient.Start();}#endregion#region 接收消息/// <summary>/// 接收消息/// </summary>private void ReceiceMsg(){while (IsRunning){//定义一个2M缓冲区byte[] arrMsgRec = new byte[1024 * 1024 * 2];int length = -1;try{length = sockClient.Receive(arrMsgRec);}catch (SocketException){break;}catch (Exception ex){Invoke(new Action(() => this.txt_Rcv.AppendText("断开连接" + ex.Message + Environment.NewLine)));break;}if (length > 0){//表示接受到的为消息类型if (arrMsgRec[0] == 0){string strMsg = Encoding.UTF8.GetString(arrMsgRec, 1, length-1);string Msg = "[接收]     " + strMsg + Environment.NewLine;Invoke(new Action(() => this.txt_Rcv.AppendText(Msg)));}//表示接收到的为文件类型if (arrMsgRec[0] == 1){Invoke(MyFileSave, arrMsgRec,length);}}}}#endregion#region 委托方法体private void FileSave(byte[] bt, int length){try{SaveFileDialog sfd = new SaveFileDialog();sfd.Filter = "word files(*.docx)|*.docx|txt files(*.txt)|*.txt|xls files(*.xls)|*.xls|All files(*.*)|*.*";if (sfd.ShowDialog() == DialogResult.OK){string fileSavePath = sfd.FileName;using (FileStream fs = new FileStream(fileSavePath, FileMode.Create)){fs.Write(bt, 1, length - 1);Invoke(new Action(() => this.txt_Rcv.AppendText("[保存]     保存文件成功" + fileSavePath+Environment.NewLine)));}}}catch (Exception ex){MessageBox.Show("保存异常" + ex.Message, "保存文件出现异常");}}#endregion#region 发送消息/// <summary>/// 发送消息/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_Send_Click(object sender, EventArgs e){string strMsg = "来自" + this.txt_Name.Text.Trim() + ":  " + this.txt_Send.Text.Trim();byte[] arrMsg = Encoding.UTF8.GetBytes(strMsg);byte[] arrSend = new byte[arrMsg.Length + 1];arrSend[0] = 0;Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);sockClient.Send(arrSend);Invoke(new Action(() => this.txt_Rcv.AppendText("[发送]     " + this.txt_Send.Text.Trim() + Environment.NewLine)));}#endregion#region 窗体关闭事件/// <summary>/// 窗体关闭事件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void FrmTCPClient_FormClosing(object sender, FormClosingEventArgs e){IsRunning = false;sockClient?.Close();}#endregion#region 选择文件/// <summary>/// 选择文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_SelectFile_Click(object sender, EventArgs e){OpenFileDialog ofd = new OpenFileDialog();ofd.InitialDirectory = "D:\\";if (ofd.ShowDialog() == DialogResult.OK){this.txt_SelectFile.Text = ofd.FileName;}}#endregion#region 发送文件/// <summary>/// 发送文件/// </summary>/// <param name="sender"></param>/// <param name="e"></param>private void btn_SendFile_Click(object sender, EventArgs e){if (string.IsNullOrEmpty(txt_SelectFile.Text)){MessageBox.Show("请选择您要发送的文件!", "发送文件提示");return;}using (FileStream fs = new FileStream(txt_SelectFile.Text, FileMode.Open)){string filename = Path.GetFileName(txt_SelectFile.Text);string StrMsg = "发送文件为:" + filename;byte[] arrMsg = Encoding.UTF8.GetBytes(StrMsg);byte[] arrSend = new byte[arrMsg.Length + 1];arrSend[0] = 0;Buffer.BlockCopy(arrMsg, 0, arrSend, 1, arrMsg.Length);sockClient.Send(arrSend);byte[] arrfileSend = new byte[1024 * 1024 * 2];int length = fs.Read(arrfileSend, 0, arrfileSend.Length);byte[] arrfile = new byte[length + 1];arrfile[0] = 1;Buffer.BlockCopy(arrfileSend, 0, arrfile, 1, length);sockClient.Send(arrfile);}}#endregion}
}

        3、启动文件Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;namespace SocketTCP
{static class Program{/// <summary>/// 应用程序的主入口点。/// </summary>[STAThread]static void Main(){Application.EnableVisualStyles();Application.SetCompatibleTextRenderingDefault(false);Application.Run(new FrmTCPServer());}}
}

结果展示 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/37249.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

1、案例二:使用Pandas库进行进行机器学习建模步骤【Python人工智能】

在人工智能和机器学习项目中&#xff0c;数据处理是一个至关重要的环节。Pandas是Python中一个强大的数据处理库&#xff0c;它提供了高效、灵活的数据结构和数据分析工具。下面是一个使用Pandas库进行数据处理的例子&#xff0c;涉及数据清洗、特征工程和基本的统计分析。 示…

AI大模型怎么备案?

随着人工智能技术的飞速发展&#xff0c;生成式AI正逐渐渗透到我们的日常生活和各行各业中。从文本创作到艺术设计&#xff0c;从虚拟助手到智能客服&#xff0c;AI的身影无处不在。然而&#xff0c;技术的创新与应用&#xff0c;离不开法律的规范与引导。为进一步保障和监管AI…

cocos creator 调试插件

适用 Cocos Creator 3.4 版本&#xff0c;cocos creator 使用google浏览器调试时&#xff0c;我们可以把事实运行的节点以节点树的形式显示在浏览器上&#xff0c;支持运行时动态调整位置等、、、 将下载的preview-template插件解压后放在工程根目录下&#xff0c;然后重新运行…

kubernetes Deployment yaml文件解析

一、yaml文件示例 apiVersion: apps/v1 kind: Deployment metadata:labels:app: nginxname: nginxnamespace: mtactor spec:replicas: 4revisionHistoryLimit: 10selector:matchLabels:app: nginxstrategy:rollingUpdate:maxSurge: 25%maxUnavailable: 25%type: RollingUpdate…

C++:inline关键字nullptr

inline关键字 C中inline使用关键点强调 (1)inline是一种“用于实现的关键字”&#xff0c;而不是一种“用于声明的关键字”&#xff0c;所以关键字 inline 必须与函数定义体放在一起&#xff0c;而不是和声明放在一起 (2)如果希望在多个c文件中使用&#xff0c;则inline函数应…

树莓派4B_OpenCv学习笔记15:OpenCv定位物体实时坐标

今日继续学习树莓派4B 4G&#xff1a;&#xff08;Raspberry Pi&#xff0c;简称RPi或RasPi&#xff09; 本人所用树莓派4B 装载的系统与版本如下: 版本可用命令 (lsb_release -a) 查询: Opencv 版本是4.5.1&#xff1a; 今日学习 OpenCv定位物体实时位置&#xff0c;代码来源是…

阿里AIDC - 杭州 - 渗透测试岗

渗透测试岗 - 阿里AIDC - 杭州 面试开始 一、自我介绍 - 2分钟二、面试官提问与个人对答三、问面试官问题面试结束 结果&#xff1a;个人觉得悬&#xff0c;但是对方很有礼貌&#xff0c;说话态度也非常好总结&#xff1a;其实问题问的并不是特别难&#xff0c;主要是自己对攻击…

操作系统期末复习(对抽象概念的简单形象化)

操作系统 引论 定义与基本概念&#xff1a;操作系统是计算机硬件与用户之间的桥梁&#xff0c;类似于家中的管家&#xff0c;它管理硬件资源&#xff08;如CPU、内存、硬盘&#xff09;&#xff0c;并为用户提供方便的服务&#xff08;应用程序执行、文件管理等&#xff09;。…

从 Linux 向 Windows 传文件和从 Windows 向 Linux 传文件的方法

这两种传递文件的方式是可行的&#xff0c;下面是对每种方式的具体说明和步骤&#xff1a; 1. 从 Linux 向 Windows 传文件 使用 Python 的 HTTP 服务器&#xff0c;可以在 Linux 端快速搭建一个简单的文件服务器。 步骤如下&#xff1a; 在 Linux 终端中&#xff0c;进入你…

IDEA SpringBoot整合SpringData JPA(保姆级教程,超详细!!!)

目录 1. 简介 2. 创建SpringBoot项目 3. Maven依赖引入 4. 修改application.properties配置文件 5. Entity实体类编写 6. Dao层接口开发 7. 测试接口开发 8. 程序测试 1. 简介 本博客将详细介绍在IDEA中&#xff0c;如何整合SpringBoot与SpringData JPA&#xff0c;以…

用于程序搜索的智能融合算法的设计与实现(C++,已用于程序中)

该程序搜索算法是我最近写的软件中使用到的算法&#xff0c;软件的项目地址如下&#xff1a;https://github.com/ghost-him/QuickLaunch/。建议打开源码&#xff0c;找到对应的代码后再阅读本文章。 该算法已经应用在软件中&#xff0c;并且取得了令我自己很满意的效果。 前言…

TIOBE 6月榜单出炉!编程语言地位大洗牌,谁才是王?

C历史上首次超越C&#xff01;&#xff01;&#xff01; TIOBE 公布了 2024 年 6 月编程语言的排行榜&#xff1a;https://www.tiobe.com/tiobe-index/ 排行榜 以下列出的语言代表了第51至第100名。由于它们之间的差异相对较小&#xff0c;编程语言仅以字母顺序列出。 ABC, A…

如何实现HPC数据传输的高效流转,降本增效?

高性能计算&#xff08;HPC&#xff09;在多个行业中都有应用&#xff0c;涉及到HPC数据传输的行业包括但不限于&#xff1a; 1.科学研究&#xff1a;在物理学、化学、生物学、地球科学等领域进行模拟和建模。 2.工程和产品设计&#xff1a;进行复杂系统的设计和分析&#xf…

CesiumJS【Basic】- #023 加载webm文件(Entity方式)

文章目录 加载webm文件(Entity方式)1 目标2 代码2.1 main.ts3 资源文件加载webm文件(Entity方式) 1 目标 使用Entity方式加载webm文件 2 代码 2.1 main.ts /** @Author: alan.lau* @Date: 2024-06-16 11:15:48* @LastEditTime: 2024-06-16 11:43:02* @LastEditors: al…

江山欧派杯2024全国华佗五禽戏线上线下观摩交流比赛在亳州开幕

6月28日&#xff0c;2024全国华佗五禽戏线上线下观摩交流比赛在安徽省亳州市开幕。 此次比赛是由安徽省亳州市文化旅游体育局和安徽省非物质文化遗产保护中心主办、亳州市华佗五禽戏协会&#xff08;国家级非遗华佗五禽戏保护单位&#xff09;和亳州市传统华佗五禽戏俱乐部&…

linux 设置程序自启动

程序随系统开机自启动的方法有很多种&#xff0c; 这里介绍一种简单且常用的&#xff0c; 通过系统的systemd服务进行自启动。 第一步&#xff1a; 新建一个.service文件 sudo vim /etc/systemd/system/myservice.service[Unit] DescriptionMy Service #Afternetwork.target[…

【鸿蒙】稍微理解一下Stage模型

鸿蒙的Stage模型是HarmonyOS多端统一的应用开发框架中的一个核心概念&#xff0c;用于描述应用的界面层次结构和组件之间的关系。下面将详细解析Stage模型的主要组成部分和特点&#xff1a; 模型组成&#xff1a; UIAbility组件&#xff1a;这是应用中负责绘制用户界面的组件&a…

LeetCode:经典题之206、92 题解及延伸

系列目录 88.合并两个有序数组 52.螺旋数组 567.字符串的排列 643.子数组最大平均数 150.逆波兰表达式 61.旋转链表 160.相交链表 83.删除排序链表中的重复元素 389.找不同 1491.去掉最低工资和最高工资后的工资平均值 896.单调序列 206.反转链表 92.反转链表II 141.环形链表 …

【应用开发二】GPIO操控(输出、输入、中断)

1 操控GPIO方式 控制目录&#xff1a;/sys/class/gpio /sys/class/gpio目录下文件如下图所示&#xff1a; 1.1 gpiochipX目录 功能&#xff1a;当前SoC所包含的所有GPIO控制器 i.mx6ull一共包含5个GPIO控制器&#xff0c;分别为GPIO1~5分别对应gpiochip0、gpiochip32、gpi…

视频共享融合赋能平台LntonCVS安防监控平台现场方案实现和应用场景

LntonCVS国标视频融合云平台采用端-边-云一体化架构&#xff0c;部署简单灵活&#xff0c;功能多样化。支持多协议&#xff08;GB28181/RTSP/Onvif/海康SDK/Ehome/大华SDK/RTMP推流等&#xff09;和多类型设备接入&#xff08;IPC/NVR/监控平台&#xff09;。主要功能包括视频直…