网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

怎么在C#.NET中使用Socket框架-创新互联

这期内容当中小编将会给大家带来有关怎么在C# .NET中使用Socket框架,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

成都创新互联公司是一家集网站建设,湾里企业网站建设,湾里品牌网站建设,网站定制,湾里网站建设报价,网络营销,网络优化,湾里网站推广为一体的创新建站企业,帮助传统企业提升企业形象加强企业竞争力。可充分满足这一群体相比中小企业更为丰富、高端、多元的互联网需求。同时我们时刻保持专业、时尚、前沿,时刻以成就客户成长自我,坚持不断学习、思考、沉淀、净化自己,让我们为更多的企业打造出实用型网站。

1、首先简单讲下C#中Socket的简单使用。

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

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

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

第四步:客户端和服务端已经建立双工通信(即双向通信),客户端和服务端可以轻松方便的给彼此发送信息。

至于简单使用的具体实现代码全部被我封装到项目中了,如果需要学习简单的实现,可以看我的源码,也可以自行百度,有很多的教程

2、核心,框架的使用

其实,说其为框架,可能有点牵强,因为每个人对框架都有自己的理解,但是类库和框架又有什么本质区别呢?全部都是代码~哈哈,扯远了

首先,空说无凭,先放上所有的代码:

服务端源文件:

SocketServer.cs

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;

namespace Coldairarrow.Util.Sockets
{
 /// 
 /// Socket服务端
 /// 
 public class SocketServer
 {
  #region 构造函数

  /// 
  /// 构造函数
  /// 
  /// 监听的IP地址
  /// 监听的端口
  public SocketServer(string ip, int port)
  {
   _ip = ip;
   _port = port;
  }

  /// 
  /// 构造函数,监听IP地址默认为本机0.0.0.0
  /// 
  /// 监听的端口
  public SocketServer(int port)
  {
   _ip = "0.0.0.0";
   _port = port;
  }

  #endregion

  #region 内部成员

  private Socket _socket = null;
  private string _ip = "";
  private int _port = 0;
  private bool _isListen = true;
  private void StartListen()
  {
   try
   {
    _socket.BeginAccept(asyncResult =>
    {
     try
     {
      Socket newSocket = _socket.EndAccept(asyncResult);

      //马上进行下一轮监听,增加吞吐量
      if (_isListen)
       StartListen();

      SocketConnection newClient = new SocketConnection(newSocket, this)
      {
       HandleRecMsg = HandleRecMsg == null ? null : new Action(HandleRecMsg),
       HandleClientClose = HandleClientClose == null ? null : new Action(HandleClientClose),
       HandleSendMsg = HandleSendMsg == null ? null : new Action(HandleSendMsg),
       HandleException = HandleException == null ? null : new Action(HandleException)
      };

      newClient.StartRecMsg();
      ClientList.AddLast(newClient);

      HandleNewClientConnected?.Invoke(this, newClient);
     }
     catch (Exception ex)
     {
      HandleException?.Invoke(ex);
     }
    }, null);
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
   }
  }

  #endregion

  #region 外部接口

  /// 
  /// 开始服务,监听客户端
  /// 
  public void StartServer()
  {
   try
   {
    //实例化套接字(ip4寻址协议,流式传输,TCP协议)
    _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //创建ip对象
    IPAddress address = IPAddress.Parse(_ip);
    //创建网络节点对象包含ip和port
    IPEndPoint endpoint = new IPEndPoint(address, _port);
    //将 监听套接字绑定到 对应的IP和端口
    _socket.Bind(endpoint);
    //设置监听队列长度为Int32大值(同时能够处理连接请求数量)
    _socket.Listen(int.MaxValue);
    //开始监听客户端
    StartListen();
    HandleServerStarted?.Invoke(this);
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
   }
  }

  /// 
  /// 所有连接的客户端列表
  /// 
  public LinkedList ClientList { get; set; } = new LinkedList();

  /// 
  /// 关闭指定客户端连接
  /// 
  /// 指定的客户端连接
  public void CloseClient(SocketConnection theClient)
  {
   theClient.Close();
  }

  #endregion

  #region 公共事件

  /// 
  /// 异常处理程序
  /// 
  public Action HandleException { get; set; }

  #endregion

  #region 服务端事件

  /// 
  /// 服务启动后执行
  /// 
  public Action HandleServerStarted { get; set; }

  /// 
  /// 当新客户端连接后执行
  /// 
  public Action HandleNewClientConnected { get; set; }

  /// 
  /// 服务端关闭客户端后执行
  /// 
  public Action HandleCloseClient { get; set; }

  #endregion

  #region 客户端连接事件

  /// 
  /// 客户端连接接受新的消息后调用
  /// 
  public Action HandleRecMsg { get; set; }

  /// 
  /// 客户端连接发送消息后回调
  /// 
  public Action HandleSendMsg { get; set; }

  /// 
  /// 客户端连接关闭后回调
  /// 
  public Action HandleClientClose { get; set; }

  #endregion
 }
}
using System;
using System.Net.Sockets;
using System.Text;

namespace Coldairarrow.Util.Sockets
{
 /// 
 /// Socket连接,双向通信
 /// 
 public class SocketConnection
 {
  #region 构造函数

  public SocketConnection(Socket socket,SocketServer server)
  {
   _socket = socket;
   _server = server;
  }

  #endregion

  #region 私有成员
  
  private readonly Socket _socket;
  private bool _isRec=true;
  private SocketServer _server = null;
  private bool IsSocketConnected()
  {
   bool part1 = _socket.Poll(1000, SelectMode.SelectRead);
   bool part2 = (_socket.Available == 0);
   if (part1 && part2)
    return false;
   else
    return true;
  }

  #endregion

  #region 外部接口

  /// 
  /// 开始接受客户端消息
  /// 
  public void StartRecMsg()
  {
   try
   {
    byte[] container = new byte[1024 * 1024 * 2];
    _socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult =>
    {
     try
     {
      int length = _socket.EndReceive(asyncResult);

      //马上进行下一轮接受,增加吞吐量
      if (length > 0 && _isRec && IsSocketConnected())
       StartRecMsg();

      if (length > 0)
      {
       byte[] recBytes = new byte[length];
       Array.Copy(container, 0, recBytes, 0, length);

       //处理消息
       HandleRecMsg?.Invoke(recBytes, this, _server);
      }
      else
       Close();
     }
     catch (Exception ex)
     {
      HandleException?.Invoke(ex);
      Close();
     }
    }, null);
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
    Close();
   }
  }

  /// 
  /// 发送数据
  /// 
  /// 数据字节
  public void Send(byte[] bytes)
  {
   try
   {
    _socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncResult =>
    {
     try
     {
      int length = _socket.EndSend(asyncResult);
      HandleSendMsg?.Invoke(bytes, this, _server);
     }
     catch (Exception ex)
     {
      HandleException?.Invoke(ex);
     }
    }, null);
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
   }
  }

  /// 
  /// 发送字符串(默认使用UTF-8编码)
  /// 
  /// 字符串
  public void Send(string msgStr)
  {
   Send(Encoding.UTF8.GetBytes(msgStr));
  }

  /// 
  /// 发送字符串(使用自定义编码)
  /// 
  /// 字符串消息
  /// 使用的编码
  public void Send(string msgStr,Encoding encoding)
  {
   Send(encoding.GetBytes(msgStr));
  }

  /// 
  /// 传入自定义属性
  /// 
  public object Property { get; set; }

  /// 
  /// 关闭当前连接
  /// 
  public void Close()
  {
   try
   {
    _isRec = false;
    _socket.Disconnect(false);
    _server.ClientList.Remove(this);
    HandleClientClose?.Invoke(this, _server);
    _socket.Close();
    _socket.Dispose();
    GC.Collect();
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
   }
  }

  #endregion

  #region 事件处理

  /// 
  /// 客户端连接接受新的消息后调用
  /// 
  public Action HandleRecMsg { get; set; }

  /// 
  /// 客户端连接发送消息后回调
  /// 
  public Action HandleSendMsg { get; set; }

  /// 
  /// 客户端连接关闭后回调
  /// 
  public Action HandleClientClose { get; set; }

  /// 
  /// 异常处理程序
  /// 
  public Action HandleException { get; set; }

  #endregion
 }
}
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace Coldairarrow.Util.Sockets
{
 /// 
 /// Socket客户端
 /// 
 public class SocketClient
 {
  #region 构造函数

  /// 
  /// 构造函数,连接服务器IP地址默认为本机127.0.0.1
  /// 
  /// 监听的端口
  public SocketClient(int port)
  {
   _ip = "127.0.0.1";
   _port = port;
  }

  /// 
  /// 构造函数
  /// 
  /// 监听的IP地址
  /// 监听的端口
  public SocketClient(string ip, int port)
  {
   _ip = ip;
   _port = port;
  }

  #endregion

  #region 内部成员

  private Socket _socket = null;
  private string _ip = "";
  private int _port = 0;
  private bool _isRec=true;
  private bool IsSocketConnected()
  {
   bool part1 = _socket.Poll(1000, SelectMode.SelectRead);
   bool part2 = (_socket.Available == 0);
   if (part1 && part2)
    return false;
   else
    return true;
  }

  /// 
  /// 开始接受客户端消息
  /// 
  public void StartRecMsg()
  {
   try
   {
    byte[] container = new byte[1024 * 1024 * 2];
    _socket.BeginReceive(container, 0, container.Length, SocketFlags.None, asyncResult =>
    {
     try
     {
      int length = _socket.EndReceive(asyncResult);

      //马上进行下一轮接受,增加吞吐量
      if (length > 0 && _isRec && IsSocketConnected())
       StartRecMsg();

      if (length > 0)
      {
       byte[] recBytes = new byte[length];
       Array.Copy(container, 0, recBytes, 0, length);

       //处理消息
       HandleRecMsg?.Invoke(recBytes, this);
      }
      else
       Close();
     }
     catch (Exception ex)
     {
      HandleException?.Invoke(ex);
      Close();
     }
    }, null);
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
    Close();
   }
  }

  #endregion

  #region 外部接口

  /// 
  /// 开始服务,连接服务端
  /// 
  public void StartClient()
  {
   try
   {
    //实例化 套接字 (ip4寻址协议,流式传输,TCP协议)
    _socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    //创建 ip对象
    IPAddress address = IPAddress.Parse(_ip);
    //创建网络节点对象 包含 ip和port
    IPEndPoint endpoint = new IPEndPoint(address, _port);
    //将 监听套接字 绑定到 对应的IP和端口
    _socket.BeginConnect(endpoint, asyncResult =>
    {
     try
     {
      _socket.EndConnect(asyncResult);
      //开始接受服务器消息
      StartRecMsg();

      HandleClientStarted?.Invoke(this);
     }
     catch (Exception ex)
     {
      HandleException?.Invoke(ex);
     }
    }, null);
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
   }
  }

  /// 
  /// 发送数据
  /// 
  /// 数据字节
  public void Send(byte[] bytes)
  {
   try
   {
    _socket.BeginSend(bytes, 0, bytes.Length, SocketFlags.None, asyncResult =>
    {
     try
     {
      int length = _socket.EndSend(asyncResult);
      HandleSendMsg?.Invoke(bytes, this);
     }
     catch (Exception ex)
     {
      HandleException?.Invoke(ex);
     }
    }, null);
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
   }
  }

  /// 
  /// 发送字符串(默认使用UTF-8编码)
  /// 
  /// 字符串
  public void Send(string msgStr)
  {
   Send(Encoding.UTF8.GetBytes(msgStr));
  }

  /// 
  /// 发送字符串(使用自定义编码)
  /// 
  /// 字符串消息
  /// 使用的编码
  public void Send(string msgStr, Encoding encoding)
  {
   Send(encoding.GetBytes(msgStr));
  }

  /// 
  /// 传入自定义属性
  /// 
  public object Property { get; set; }

  /// 
  /// 关闭与服务器的连接
  /// 
  public void Close()
  {
   try
   {
    _isRec = false;
    _socket.Disconnect(false);
    HandleClientClose?.Invoke(this);
   }
   catch (Exception ex)
   {
    HandleException?.Invoke(ex);
   }
  }

  #endregion

  #region 事件处理

  /// 
  /// 客户端连接建立后回调
  /// 
  public Action HandleClientStarted { get; set; }

  /// 
  /// 处理接受消息的委托
  /// 
  public Action HandleRecMsg { get; set; }

  /// 
  /// 客户端连接发送消息后回调
  /// 
  public Action HandleSendMsg { get; set; }

  /// 
  /// 客户端连接关闭后回调
  /// 
  public Action HandleClientClose { get; set; }

  /// 
  /// 异常处理程序
  /// 
  public Action HandleException { get; set; }

  #endregion
 }
}

上面放上的是框架代码,接下来介绍下如何使用

首先,服务端使用方式:

using Coldairarrow.Util.Sockets;
using System;
using System.Text;

namespace Console_Server
{
 class Program
 {
  static void Main(string[] args)
  {
   //创建服务器对象,默认监听本机0.0.0.0,端口12345
   SocketServer server = new SocketServer(12345);

   //处理从客户端收到的消息
   server.HandleRecMsg = new Action((bytes, client, theServer) =>
   {
    string msg = Encoding.UTF8.GetString(bytes);
    Console.WriteLine($"收到消息:{msg}");
   });

   //处理服务器启动后事件
   server.HandleServerStarted = new Action(theServer =>
   {
    Console.WriteLine("服务已启动************");
   });

   //处理新的客户端连接后的事件
   server.HandleNewClientConnected = new Action((theServer, theCon) =>
   {
    Console.WriteLine($@"一个新的客户端接入,当前连接数:{theServer.ClientList.Count}");
   });

   //处理客户端连接关闭后的事件
   server.HandleClientClose = new Action((theCon, theServer) =>
   {
    Console.WriteLine($@"一个客户端关闭,当前连接数为:{theServer.ClientList.Count}");
   });

   //处理异常
   server.HandleException = new Action(ex =>
   {
    Console.WriteLine(ex.Message);
   });

   //服务器启动
   server.StartServer();

   while (true)
   {
    Console.WriteLine("输入:quit,关闭服务器");
    string op = Console.ReadLine();
    if (op == "quit")
     break;
   }
  }
 }
}

客户端使用方式:

using Coldairarrow.Util.Sockets;
using System;
using System.Text;

namespace Console_Client
{
 class Program
 {
  static void Main(string[] args)
  {
   //创建客户端对象,默认连接本机127.0.0.1,端口为12345
   SocketClient client = new SocketClient(12345);

   //绑定当收到服务器发送的消息后的处理事件
   client.HandleRecMsg = new Action((bytes, theClient) =>
   {
    string msg = Encoding.UTF8.GetString(bytes);
    Console.WriteLine($"收到消息:{msg}");
   });

   //绑定向服务器发送消息后的处理事件
   client.HandleSendMsg = new Action((bytes, theClient) =>
   {
    string msg = Encoding.UTF8.GetString(bytes);
    Console.WriteLine($"向服务器发送消息:{msg}");
   });

   //开始运行客户端
   client.StartClient();

   while (true)
   {
    Console.WriteLine("输入:quit关闭客户端,输入其它消息发送到服务器");
    string str = Console.ReadLine();
    if (str == "quit")
    {
     client.Close();
     break;
    }
    else
    {
     client.Send(str);
    }
   }
  }
 }
}

最后运行测试截图:

怎么在C# .NET中使用Socket框架

上述就是小编为大家分享的怎么在C# .NET中使用Socket框架了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联成都网站建设公司行业资讯频道。

另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。


分享题目:怎么在C#.NET中使用Socket框架-创新互联
URL地址:http://bjjierui.cn/article/dcjjec.html

其他资讯