异步原理
套接字编程原理:延续文件作用思想,打开-读写-关闭的模式。
C/S编程模式如下:
Ø 服务器端:
打开通信通道,告诉本地机器,愿意在该通道上接受客户请求——监听,等待客户请求——接受请求,创建专用链接进行读写——处理完毕,关闭专用链接——关闭通信通道(当然其中监听到关闭专用链接可以重复循环)
Ø 客户端:打开通信通道,连接服务器——数据交互——关闭信道。
Socket通信方式:
Ø 同步:客户端在发送请求之后必须等到服务器回应之后才可以发送下一条请求。串行运行
Ø 异步:客户端请求之后,不必等到服务器回应之后就可以发送下一条请求。并行运行
套接字模式:
Ø 阻塞:执行此套接字调用时,所有调用函数只有在得到返回结果之后才会返回。在调用结果返回之前,当前进程会被挂起。即此套接字一直被阻塞在网络调用上。
Ø 非阻塞:执行此套接字调用时,调用函数即使得不到得到返回结果也会返回。
套接字工作步骤:
Ø 服务器监听:监听时服务器端套接字并不定位具体客户端套接字,而是处于等待链接的状态,实时监控网络状态
Ø 客户端链接:客户端发出链接请求,要连接的目标是服务器端的套接字。为此客户端套接字必须描述服务器端套接字的服务器地址与端口号。
Ø 链接确认:是指服务器端套接字监听到客户端套接字的链接请求时,它响应客户端链接请求,建立一个新的线程,把服务器端套接字的描述发送给客户端,一旦客户端确认此描述,则链接建立好。而服务器端的套接字继续处于监听状态,继续接受其他客户端套接字请求。
源码
Server源码:
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 ConsoleApp1
{
public class Conn
{ //定义数据最大长度
public const int data = 1024;
//Socket
public Socket socket;
//是否使用
public bool isUse = false;
//Buff
public byte[] readBuff = new byte[data];
public int buffCount = 0;
//构造函数
public Conn()
{
readBuff = new byte[data];
}
//初始化
public void Init(Socket socket)
{
this.socket = socket;
isUse = true;
buffCount = 0;
}
//缓冲区剩余的字节数
public int BuffRemain()
{
return data - buffCount;
}
//获取客户端地址
public string GetAdress()
{
if (!isUse)
return "无法获取地址";
return socket.RemoteEndPoint.ToString();
}
//关闭
public void Close()
{
if (!isUse)
return;
Console.WriteLine("[断开链接]" + GetAdress());
socket.Close();
isUse = false;
}
}
public class Program
{
/// <summary>
/// 创建多个Conn管理客户端的连接
/// </summary>
public static Conn[] conns;
/// <summary>
/// 最大连接数
/// </summary>
public static int maxConn = 50;
/// <summary>
/// 将Socket定义为全局变量
/// </summary>
private static Socket serverSocket;
/// <summary>
/// 获取链接池索引,返回负数表示获取失败
/// </summary>
/// <returns></returns>
public static int NewIndex()
{
if (conns == null)
return -1;
for (int i = 0; i < conns.Length; i++)
{
if (conns[i] == null)
{
conns[i] = new Conn();
return i;
}
else if (conns[i].isUse == false)
{
return i;
}
}
return -1;
}
static void Main(string[] args)
{
//创建多个链接池,表示创建maxConn最大客户端
conns = new Conn[maxConn];
for (int i = 0; i < maxConn; i++)
{
conns[i] = new Conn();
}
serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
serverSocket.Bind(ipEndPoint);//绑定IP和端口号
serverSocket.Listen(maxConn);//开始监听端口,0为监听无限个客户端
Console.WriteLine("[服务器]启动成功");
//开始调用异步连接
serverSocket.BeginAccept(AcceptCb, null);
//按下quit退出程序
while (true)
{
if (Console.ReadLine() == "quit") return;
}
}
/// <summary>
/// Accept回调
/// </summary>
/// <param name="ar"></param>
static void AcceptCb(IAsyncResult ar)
{
try
{
Socket socket = serverSocket.EndAccept(ar);//尝试进行异步连接
int index = NewIndex();
if (index < 0)
{
socket.Close();
Console.Write("[警告]链接已满");
}
else
{
Conn conn = conns[index];
conn.Init(socket);
string adr = conn.GetAdress();
Console.WriteLine("客户端连接 [" + adr + "] conn池ID:" + index);
conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(), SocketFlags.None, ReceiveCb, conn);
}
serverSocket.BeginAccept(AcceptCb, null);
}
catch (Exception e)
{
Console.WriteLine("AcceptCb失败:" + e.Message);
}
}
/// <summary>
/// 接收回调
/// </summary>
/// <param name="ar"></param>
static void ReceiveCb(IAsyncResult ar)
{
Conn conn = (Conn)ar.AsyncState;
try
{
int count = conn.socket.EndReceive(ar);
//关闭信号
if (count <= 0)
{
Console.WriteLine("收到 [" + conn.GetAdress() + "] 断开链接");
conn.Close();
return;
}
//数据处理
string str = Encoding.UTF8.GetString(conn.readBuff, 0, count);
Console.WriteLine("收到 [" + conn.GetAdress() + "] 数据:" + str);
str = conn.GetAdress() + "发送的:" + str;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes("接收到" + str);
//广播
/*
for (int i = 0; i < conns.Length; i++)
{
if (conns[i] == null)
continue;
if (!conns[i].isUse)
continue;
Console.WriteLine("将消息转播给 " + conns[i].GetAdress());
conns[i].socket.Send(bytes);
}*/
//点播
for (int i = 0; i<=0;i++)
{
if (conns[i] == null)
continue;
if (!conns[i].isUse)
continue;
Console.WriteLine("将消息转播给 " + conns[i].GetAdress());
conns[i].socket.Send(bytes);
}
//继续接收
conn.socket.BeginReceive(conn.readBuff, conn.buffCount, conn.BuffRemain(),SocketFlags.None, ReceiveCb, conn);
}
catch (Exception e)
{
Console.WriteLine("收到 [" + conn.GetAdress() + "] 断开链接");
conn.Close();
}
}
}
}
Client源码
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 ConsoleApp1
{
public class Program
{
private static int datacount = 1024;//设置数组数据长度
private static Socket socket;
private static byte[] dataBuff = new byte[datacount];
private static string recvStr;
static void Main(string[] args)
{
//获取到Socket协议
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
//绑定IP与端口
IPEndPoint ipEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
socket.Connect(ipEndPoint);//与服务端进行连接
Console.WriteLine("客户端地址 " + socket.LocalEndPoint.ToString());//获取客户端地址
//开启异步接收模式
socket.BeginReceive(dataBuff, 0, datacount, SocketFlags.None, ReceiveCb, null);
socket.Send(Encoding.UTF8.GetBytes("123")); //封装好的一个Send方法,能够在方法中操作,比如说:释放资源
Send(socket, "456"); //简单的发送
while (true)
{
//向服务器发送数据
byte[] data = Encoding.UTF8.GetBytes(Console.ReadLine());//输入字符
//按下回车键发送数据
ConsoleKey inpt = Console.ReadKey().Key;
if (inpt == ConsoleKey.Enter)
{
socket.Send(data);
Console.WriteLine("发送成功");
}
}
}
private static void Send(Socket handler, String data)
{
byte[] byteData = Encoding.ASCII.GetBytes(data);
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Socket handler = (Socket)ar.AsyncState;
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCb(IAsyncResult ar)
{
//接收数据的长度
//数据处理
//将dataBuffer数组转码成字符的形式输出
//dataBuffer:需要转码的数组
//0:从数组的长度,0开始读取。
//count :读取数组的最大长度
int count = socket.EndReceive(ar);
if(count>0) //当接受数据长度大于0时处理
{
string str = System.Text.Encoding.UTF8.GetString(dataBuff, 0, count);
//获取服务器端的数据
Console.WriteLine("获取服务端的数据:" + str);
//继续接收
socket.BeginReceive(dataBuff, 0, datacount, SocketFlags.None, ReceiveCb, null);
}
}
}
}
版权属于: 顾锦歌——发现生活的美!
本文链接: https://main.huat.fun/index.php/archives/13/
本文最后更新于2022年01月08日 ,已超过1111天没有更新,若内容或图片失效,请留言反馈。
本文允许转载,但请在转载时请以超链接或其它形式标明文章出处
Your go-to source for leads. We can provide business to business and business to consumer leads, custom-tailored to your needs. CustomDatabases.org
Hi, It is with sad regret to inform you TopDataList.com is shutting down. We are ceasing operations on TopDataList.com and have made our leads available at a $149 once off fee. Visit us on TopDataList.com Regards, Otilia
Hello, from CustomData.click we are a provider of unique databases that could help your business. Please visit us at CustomData.click to see if we can help you. Regards, Ervin
Hello. It is with sad regret to inform you TopDataList.com is shutting down. We have made all our databases available for you for a once off fee. Visit us on TopDataList.com
ZippyLeads.org is running an easter special till the 18th of April. Get all the leads you need for your company with our easter special.
Hello. My name is Johan Fourie and I am looking to sell DataList.biz. We are a data company that has been in the industry for 12 years. We do around $170k/year in revenue. 1) I am looking to sell 50% of the business for $5k. 2) It would be helpful if you are knowledgeable about the Data Business. 3) I am looking for someone that is willing to take over administration, support, client relations. 4) I will continue to do the marketing for new products. 5) You will accept all future income and pay me from it. Please contact me on WhatsApp +27 72 280 1952 or my personal email: johanfourieinc@gmail.com if you are interested in this and we can have a call. Regards, Johan Fourie
Hi, I am interested in some of your products. Please give me a call on +1 304-873-4360
欢迎加入 Typecho 大家族