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

C#中Socket的简单使用

以前学过的Socket,后来没怎么用过,就基本忘了,所以闲来时重新回顾学习一番.

一.Socket的概念

Socket其实并不是一个协议,而是为了方便使用TCP或UDP而抽象出来的一层,是位于应用层和传输控制层之间的一组接口.

当两台主机通信是,必须通过Socket连接,Socket则利用TCP/IP协议建立TCP连接.TCP连接则更依赖于底层的IP协议.Socket是控制层传输协议.

双向的通信连接实现数据的交换,连接的一端成为一个Socket.

二.网络通信三要素

  • IP地址(网络上主机设备的唯一标识)
  • 端口号(定位程序)
  •      有效端口:0~65535,其中0~1024由系统使用,开发中一般使用1024以上端口.
  • 传输协议(用什么样的方式进行交互)
  •      常见协议:TCP(面向连接,提供可靠的服务),UDP(无连接,传输速度快)

三.Socket的通信流程

四.C#中Socket的简单使用步骤

第一步:服务端监听某个端口

第二步:客户端向服务端地址和端口发起Socket请求

第三步:服务器接收连接请求后创建Socket连接,并维护这个连接队列

第四步:客户端和服务端就建立起了双工同信,客户端与服务端就可以实现彼此发送消息

五.简单代码实例

1.服务端代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;namespace SocketUtil
{public class SocketServer{private string _ip = string.Empty;private int _port = 0;private Socket _socket = null;private byte[] buffer = new byte[1024 * 1024 * 2];/// <summary>/// 构造函数/// </summary>/// <param name="ip">监听的IP</param>/// <param name="port">监听的端口</param>public SocketServer(string ip, int port){this._ip = ip;this._port = port;}public SocketServer(int port){this._ip = "0.0.0.0";this._port = port;}public void StartListen(){try{//1.0 实例化套接字(IP4寻找协议,流式协议,TCP协议)_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//2.0 创建IP对象IPAddress address = IPAddress.Parse(_ip);//3.0 创建网络端口,包括ip和端口IPEndPoint endPoint = new IPEndPoint(address, _port);//4.0 绑定套接字_socket.Bind(endPoint);//5.0 设置最大连接数_socket.Listen(int.MaxValue);Console.WriteLine("监听{0}消息成功", _socket.LocalEndPoint.ToString());//6.0 开始监听Thread thread = new Thread(ListenClientConnect);thread.Start();}catch (Exception ex){}}/// <summary>/// 监听客户端连接/// </summary>private void ListenClientConnect(){try{while (true){//Socket创建的新连接Socket clientSocket = _socket.Accept();clientSocket.Send(Encoding.UTF8.GetBytes("服务端发送消息:"));Thread thread = new Thread(ReceiveMessage);thread.Start(clientSocket);}}catch (Exception){}}/// <summary>/// 接收客户端消息/// </summary>/// <param name="socket">来自客户端的socket</param>private void ReceiveMessage(object socket){Socket clientSocket = (Socket)socket;while (true){try{//获取从客户端发来的数据int length = clientSocket.Receive(buffer);Console.WriteLine("接收客户端{0},消息{1}", clientSocket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer, 0, length));}catch (Exception ex){Console.WriteLine(ex.Message);clientSocket.Shutdown(SocketShutdown.Both);clientSocket.Close();break;}}}}
}

2.客户端代码

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 SocketUtil
{public class SocketClient{private string _ip = string.Empty;private int _port = 0;private Socket _socket = null;private byte[] buffer = new byte[1024 * 1024 * 2];/// <summary>/// 构造函数/// </summary>/// <param name="ip">连接服务器的IP</param>/// <param name="port">连接服务器的端口</param>public SocketClient(string ip, int port){this._ip = ip;this._port = port;}public SocketClient(int port){this._ip = "127.0.0.1";this._port = port;}/// <summary>/// 开启服务,连接服务端/// </summary>public void StartClient(){try{//1.0 实例化套接字(IP4寻址地址,流式传输,TCP协议)_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//2.0 创建IP对象IPAddress address = IPAddress.Parse(_ip);//3.0 创建网络端口包括ip和端口IPEndPoint endPoint = new IPEndPoint(address, _port);//4.0 建立连接_socket.Connect(endPoint);Console.WriteLine("连接服务器成功");//5.0 接收数据int length = _socket.Receive(buffer);Console.WriteLine("接收服务器{0},消息:{1}", _socket.RemoteEndPoint.ToString(), Encoding.UTF8.GetString(buffer,0,length));//6.0 像服务器发送消息for (int i = 0; i < 10; i++){Thread.Sleep(2000);string sendMessage = string.Format("客户端发送的消息,当前时间{0}", DateTime.Now.ToString());_socket.Send(Encoding.UTF8.GetBytes(sendMessage));Console.WriteLine("像服务发送的消息:{0}", sendMessage);}}catch (Exception ex){_socket.Shutdown(SocketShutdown.Both);_socket.Close();Console.WriteLine(ex.Message);}Console.WriteLine("发送消息结束");Console.ReadKey();}}
}

3.分别开启客户端和服务端

using SocketUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SocketClientApp
{class Program{static void Main(string[] args){SocketClient client = new SocketClient(8888);client.StartClient();Console.ReadKey();}}
}
using SocketUtil;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SocketServerApp
{class Program{static void Main(string[] args){SocketServer server = new SocketServer(8888);server.StartListen();Console.ReadKey();}}
}

4. 运行效果图

http://www.xdnf.cn/news/11193.html

相关文章:

  • 注册系统热键 RegisterHotKey()
  • Android中ProgressDialog的使用
  • BP神经网络算法基本原理,bp神经网络算法详解
  • m3u8直播测试地址
  • 面向对象设计的八大基本原则
  • VMware虚拟机Windows 10安装使用教程(非常详细)从零基础入门到精通,看完这一篇就够了_vmware安装windows10
  • BUMO 区块链开发文档
  • Dogfooding-爱奇艺移动端后台灰度环境优化实践
  • Union和Union All的使用
  • jQuery.serializeArray() 函数详解
  • C/C++编程:log4cpp使用学习
  • wait,notify/notifyAll的使用及实现原理
  • ObjectDock
  • Java 10正式发布,带来了这些新特性
  • Coqui:创建逼真的生成式人工智能语音
  • 在网络安全领域,比较牛的中国黑客有哪些?
  • git clone 遇到问题:fatal: unable to access ‘https://github.comxxxxxxxxxxx‘: Failed to connect to xxxxxxx
  • iOS开发进阶(一):iOS原生开发环境搭建步骤详解_ios编译环境搭建
  • 关于connectionstring字符串的那点事
  • Python OpenCV 3.x 示例:6~11
  • cache介绍及问题解决
  • 原始数据哪里找?这些网站要用好!200个国内外经济/金融/行研/咨询数据网站大全(附链接)...
  • Linux系统中rpm命令用法详解
  • 华为3108raid安linux,华为服务器 RAID卡配置 SR430 LSISAS3108(Legacy/Dual模式)传统模式
  • CorelDRAW X4 SP2 简体中文正式版精简增强版
  • 简易日志告警系统
  • 群晖上搭建teamspeak3语音服务器
  • 如何实现两地星三角启动
  • Event事件学习实用路线(9)——Event事件之键盘事件——案例:键盘操作元素位置——案例:键盘事件组合键控制
  • 【交替方向乘子方法】ADOM: 基于ADMM的遥感图像条纹噪声去除优化模型(Matlab代码实现)