QQ登录

只需要一步,快速开始

APP扫码登录

只需要一步,快速开始

手机号码,快捷登录

泡泡马甲APP 更多内容请下载泡泡马甲手机客户端APP 立即下载 ×
查看: 3296|回复: 0

[C#] C# Socket通信

[复制链接]

等级头衔

积分成就    金币 : 2806
   泡泡 : 1516
   精华 : 6
   在线时间 : 1244 小时
   最后登录 : 2024-5-5

丰功伟绩

优秀达人突出贡献荣誉管理论坛元老

联系方式
发表于 2021-12-2 10:46:15 | 显示全部楼层 |阅读模式
概述
7 [# L6 ^/ }& T* x: l5 Q- q       所谓套接字(Socket),就是对网络中不同主机上的应用进程之间进行双向通信的端点的抽象。一个套接字就是网络上进程通信的一端,提供了应用层进程利用网络协议交换数据的机制。从所处的地位来讲,套接字上联应用进程,下联网络协议栈,是应用程序通过网络协议进行通信的接口,是应用程序与网络协议根进行交互的接口。6 C4 E$ s) I% T9 v, x2 t+ t, R5 U
       套接字是通信的基石,是支持TCP/IP协议的路通信的基本操作单元。可以将套接字看作不同主机间的进程进行双间通信的端点,它构成了单个主机内及整个网络间的编程界面。套接字存在于通信域中,通信域是为了处理一般的线程通过套接字通信而引进的一种抽象概念。套接字通常和同一个域中的套接字交换数据(数据交换也可能穿越域的界限,但这时一定要执行某种解释程序),各种进程使用这个相同的域互相之间用Internet协议簇来进行通信。
3 j% A' X  q; a) }2 C% Z       Socket(套接字)可以看成是两个网络应用程序进行通信时,各自通信连接中的端点,这是一个逻辑上的概念。它是网络环境中进程间通信的API(应用程序编程接口),也是可以被命名和寻址的通信端点,使用中的每一个套接字都有其类型和一个与之相连进程。通信时其中一个网络应用程序将要传输的一段信息写入它所在主机的 Socket中,该 Socket通过与网络接口卡(NIC)相连的传输介质将这段信息送到另外一台主机的 Socket中,使对方能够接收到这段信息。Socket是由IP地址和端口结合的,提供向应用层进程传送数据包的机制。
8 _7 K' @4 g8 G- ^6 ^服务端
. A. ]* d; M7 ^+ n, e# p1 g. U
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Windows.Forms;
  12. namespace SocketForm
  13. {
  14.     public partial class Form1 : Form
  15.     {
  16.         public Form1()
  17.         {
  18.             InitializeComponent();
  19.         }
  20.         private void bt_connnect_Click(object sender, EventArgs e)
  21.         {
  22.             try
  23.             {
  24.                 //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
  25.                 Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  26.                 IPAddress ip = IPAddress.Any;
  27.                 //创建对象端口
  28.                 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(tb_port.Text));
  29.                 socketWatch.Bind(point);//绑定端口号
  30.                 ShowMsg("监听成功!");
  31.                 socketWatch.Listen(10);//设置监听
  32.                 //创建监听线程
  33.                 Thread thread = new Thread(Listen);
  34.                 thread.IsBackground = true;
  35.                 thread.Start(socketWatch);
  36.             }
  37.             catch { }
  38.         }
  39.         /// <summary>
  40.         /// 等待客户端的连接 并且创建与之通信的Socket
  41.         /// </summary>
  42.         Socket socketSend;
  43.         void Listen(object o)
  44.         {
  45.             try
  46.             {
  47.                 Socket socketWatch = o as Socket;
  48.                 while (true)
  49.                 {
  50.                     socketSend = socketWatch.Accept();//等待接收客户端连接
  51.                     ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
  52.                     //开启一个新线程,执行接收消息方法
  53.                     Thread r_thread = new Thread(Received);
  54.                     r_thread.IsBackground = true;
  55.                     r_thread.Start(socketSend);
  56.                 }
  57.             }
  58.             catch { }
  59.         }
  60.         /// <summary>
  61.         /// 服务器端不停的接收客户端发来的消息
  62.         /// </summary>
  63.         /// <param name="o"></param>
  64.         void Received(object o)
  65.         {
  66.             try
  67.             {
  68.                 Socket socketSend = o as Socket;
  69.                 while (true)
  70.                 {
  71.                     //客户端连接服务器成功后,服务器接收客户端发送的消息
  72.                     byte[] buffer = new byte[1024 * 1024 * 3];
  73.                     //实际接收到的有效字节数
  74.                     int len = socketSend.Receive(buffer);
  75.                     if (len == 0)
  76.                     {
  77.                         break;
  78.                     }
  79.                     string str = Encoding.UTF8.GetString(buffer, 0, len);
  80.                     ShowMsg(socketSend.RemoteEndPoint + ":" + str);
  81.                 }
  82.             }
  83.             catch { }
  84.         }
  85.         /// <summary>
  86.         /// 服务器向客户端发送消息
  87.         /// </summary>
  88.         /// <param name="str"></param>
  89.         void Send(string str) {
  90.             byte[] buffer = Encoding.UTF8.GetBytes(str);
  91.             socketSend.Send(buffer);
  92.         }
  93.         void ShowMsg(string msg)
  94.         {
  95.             listBox1.Items.Add(msg + "\r\n");
  96.         }
  97.         private void Form1_Load(object sender, EventArgs e)
  98.         {
  99.             Control.CheckForIllegalCrossThreadCalls = false;
  100.         }
  101.         private void bt_send_Click(object sender, EventArgs e)
  102.         {
  103.             Send(txt_msg.Text.Trim());
  104.         }
  105.     }
  106. }
客户端
; v% q, ~1 |" q9 I
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Net;
  8. using System.Net.Sockets;
  9. using System.Text;
  10. using System.Threading;
  11. using System.Windows.Forms;
  12. namespace SocketClient
  13. {
  14.     public partial class Form1 : Form
  15.     {
  16.         public Form1()
  17.         {
  18.             InitializeComponent();
  19.         }
  20.         Socket socketSend;
  21.         private void bt_connect_Click(object sender, EventArgs e)
  22.         {
  23.             try
  24.             {
  25.                 //创建客户端Socket,获得远程ip和端口号
  26.                 socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
  27.                 IPAddress ip = IPAddress.Parse(txt_ip.Text);
  28.                 IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txt_port.Text));
  29.                 socketSend.Connect(point);
  30.                 ShowMsg("连接成功!");
  31.                 //开启新的线程,不停的接收服务器发来的消息
  32.                 Thread c_thread = new Thread(Received);
  33.                 c_thread.IsBackground = true;
  34.                 c_thread.Start();
  35.             }
  36.             catch (Exception){
  37.                 ShowMsg("IP或者端口号错误...");
  38.             }
  39.         }
  40.         void ShowMsg(string str)
  41.         {
  42.             textBox1.AppendText(str + "\r\n");
  43.         }
  44.         /// <summary>
  45.         /// 接收服务端返回的消息
  46.         /// </summary>
  47.         void Received()
  48.         {
  49.             while (true)
  50.             {
  51.                 try
  52.                 {
  53.                     byte[] buffer = new byte[1024 * 1024 * 3];
  54.                     //实际接收到的有效字节数
  55.                     int len = socketSend.Receive(buffer);
  56.                     if (len == 0)
  57.                     {
  58.                         break;
  59.                     }
  60.                     string str = Encoding.UTF8.GetString(buffer, 0, len);
  61.                     ShowMsg(socketSend.RemoteEndPoint + ":" + str);
  62.                 }
  63.                 catch { }
  64.             }
  65.         }
  66.         /// <summary>
  67.         /// 向服务器发送消息
  68.         /// </summary>
  69.         /// <param name="sender"></param>
  70.         /// <param name="e"></param>
  71.         private void bt_send_Click(object sender, EventArgs e)
  72.         {
  73.             try
  74.             {
  75.                 string msg = txt_msg.Text.Trim();
  76.                 byte[] buffer = new byte[1024 * 1024 * 3];
  77.                 buffer = Encoding.UTF8.GetBytes(msg);
  78.                 socketSend.Send(buffer);
  79.             }
  80.             catch { }
  81.         }
  82.         private void Form1_Load(object sender, EventArgs e)
  83.         {
  84.             Control.CheckForIllegalCrossThreadCalls = false;
  85.         }
  86.     }
  87. }
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|手机版|小黑屋|paopaomj.COM ( 渝ICP备18007172号 )

GMT+8, 2024-5-12 01:48

Powered by paopaomj X3.4 © 2016-2024 sitemap

快速回复 返回顶部 返回列表