当前位置:网站首页>Unity C e-learning (IV)
Unity C e-learning (IV)
2022-04-23 04:56:00 【zzzsss123333】
Unity C# E-learning ( Four )
One . Heartbeat message
- We need to monitor the client because the network or user is disconnected
- have access to socket.Poll(1000, SelectMode.SelectRead) Disconnect when true , But this method is unstable
- We can send messages to the server every once in a while ( Heartbeat message ) To determine whether the client is connected to the server
Definition of heartbeat packet
public class HeartMsg : MsgBase
{
public override int GetLength()
{
return 8;
}
public override byte[] GetBytes()
{
var buffer = new byte[GetLength()];
var index = 0;
WriteInt(buffer,ProtoID,ref index);
WriteInt(buffer, GetLength() - 8, ref index);
return buffer;
}
public override void Reading(byte[] buffer, int startIndex = 0)
{
base.Reading(buffer, startIndex);
}
public override int ProtoID => 1002;
}
Server processing
Record the last time you received a heartbeat packet
private long _fontTime = -1;
else if (state is HeartMsg)
{
Console.WriteLine(" Received from :{0} The heartbeats of !!!",socket.RemoteEndPoint);
_fontTime = DateTime.Now.Ticks / TimeSpan.TicksPerSecond;
}
Test the time , Judge whether it's time-out
private void CheakTimeOut()
{
if(_fontTime!=-1&& DateTime.Now.Ticks / TimeSpan.TicksPerSecond - _fontTime >= 5f)
{
Program.serverSocket.AddNeedRemoveClientSocket(this);
}
}
The server removes the disconnected client
Put the client connection to be removed into the list to be removed , Remove at a specific location
Two .Socket asynchronous API( One )
public class Lesson11 : MonoBehaviour
{
private byte[] buffer = new byte[1024 * 1024];
private void Start()
{
CountDownAsync(5, () =>
{
Debug.Log(" Execution completed !");
});
CountDownAsync(5);
Debug.Log("ok");
//Socket asynchronous API
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IPv4);
// Server related
socket.BeginAccept(AcceptHandle, socket);
// Client related
socket.BeginConnect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 8080), ConnectHandle, socket);
// Dual ended universal
socket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,ReceiveHandle,socket);
// Send a message
socket.BeginSend(new byte[10], 0, 10, SocketFlags.None,SendHandle, socket);
}
private void SendHandle(IAsyncResult ar)
{
try
{
var s = ar.AsyncState as Socket;
var num = s.EndSend(ar);
}
catch (Exception e)
{
Debug.Log(e);
}
}
private void ReceiveHandle(IAsyncResult ar)
{
try
{
var s = ar.AsyncState as Socket;
var num = s.EndReceive(ar);
s.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReceiveHandle, s);
}
catch (Exception e)
{
Debug.Log(e);
}
}
private void ConnectHandle(IAsyncResult ar)
{
try
{
var s = ar.AsyncState as Socket;
s.EndConnect(ar);
}
catch (Exception e)
{
Debug.Log(e);
}
}
private void AcceptHandle(IAsyncResult result)
{
try
{
var s = result.AsyncState as Socket;
var acceptSocket = s.EndAccept(result);
s.BeginAccept(AcceptHandle, s);
}
catch (Exception e)
{
Debug.Log(e);
}
}
private void CountDownAsync(int second,UnityAction action)
{
var t = new Thread(() =>
{
while (true)
{
Debug.Log(second);
Thread.Sleep(1000);
second--;
if(second==0)
break;
}
action?.Invoke();
});
t.Start();
Debug.Log(" Start countdown ");
}
private async void CountDownAsync(int second)
{
await Task.Run(() =>
{
while (true)
{
Debug.Log(second);
Thread.Sleep(1000);
second--;
if(second==0)
break;
}
});
Debug.Log(" The countdown is over ");
}
}
3、 ... and .Socket asynchronous API( Two )
public class Lesson12 : MonoBehaviour
{
private void Start()
{
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Server side
var e1 = new SocketAsyncEventArgs();
e1.Completed += (s, args) =>
{
if (args.SocketError == SocketError.Success)
{
var acceptSocket = args.AcceptSocket;
(s as Socket)?.AcceptAsync(args);
}
else
{
Debug.Log(args.SocketError);
}
};
socket.AcceptAsync(e1);
// client
var e2 = new SocketAsyncEventArgs();
e2.Completed += (s, args) =>
{
if (args.SocketError == SocketError.Success)
{
Debug.Log(" Successful connection !");
}
else
{
Debug.Log(args.SocketError);
}
};
socket.ConnectAsync(e2);
// Send a message
var e3 = new SocketAsyncEventArgs();
e3.SetBuffer(new byte[1024], 0, 1024);
e3.Completed += (s, args) =>
{
if (args.SocketError == SocketError.Success)
{
Debug.Log(" Send successfully !");
}
else
{
Debug.Log(args.SocketError);
}
};
socket.SendAsync(e3);
// receive messages
var e4 = new SocketAsyncEventArgs();
e4.SetBuffer(new byte[1024 * 1024], 0, 1024 * 1024);
e4.Completed += (s, args) =>
{
if (args.SocketError == SocketError.Success)
{
//args.BytesTransferred Bytes received
var s1 = Encoding.UTF8.GetString(args.Buffer,0,args.BytesTransferred);
// Continue to receive... After receiving once
e4.SetBuffer(0,args.Buffer.Length);
(s as Socket)?.ReceiveAsync(args);
}
else
{
Debug.Log(args.SocketError);
}
};
socket.ReceiveAsync(e4);
}
}
版权声明
本文为[zzzsss123333]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230453444617.html
边栏推荐
- Arduino UNO r3+LCD1602+DHT11
- Use the built-in function of win to transfer files between two computers in the same LAN (the speed is the same as that between local disks)
- The 8 diagrams let you see the execution sequence of async / await and promise step by step
- Com alibaba. Common methods of fastjson
- L2-011 玩转二叉树(建树+BFS)
- 信息学奥赛一本通 1955:【11NOIP普及组】瑞士轮 | OpenJudge 4.1 4363:瑞士轮 | 洛谷 P1309 [NOIP2011 普及组] 瑞士轮
- Learning Android from scratch -- baseactivity and activitycollector
- redis和mysql区别
- 简单的拖拽物体到物品栏
- CLion+OpenCV identify ID number - detect ID number
猜你喜欢
使用model.load_state_dict()时,出现AttributeError: ‘str‘ object has no attribute ‘copy‘
深度学习笔记 —— 物体检测和数据集 + 锚框
《2021多多阅读报告》发布,95后、00后图书消费潜力攀升
Practice and exploration of knowledge map visualization technology in meituan
MySQL -- execution process and principle of a statement
【数据库】MySQL多表查询(一)
独立站运营 | FaceBook营销神器——聊天机器人ManyChat
Installation and deployment of Flink and wordcount test
Introduction to raspberry pie 3B - system installation
POI export message list (including pictures)
随机推荐
What are the redis data types
PHP counts the number of files in the specified folder
Learning Android from scratch -- baseactivity and activitycollector
Unity camera rotation with sliding effect (rotation)
DIY 一个 Excel 版的子网计算器
Repair of self calibration SPC failure of Tektronix oscilloscope dpo3054
Analysis of POM files
scp命令详解
Better way to read configuration files than properties
信息学奥赛一本通 1955:【11NOIP普及组】瑞士轮 | OpenJudge 4.1 4363:瑞士轮 | 洛谷 P1309 [NOIP2011 普及组] 瑞士轮
【数据库】MySQL单表查询
拼了!两所A级大学,六所B级大学,纷纷撤销软件工程硕士点!
Arduino UNO r3+LCD1602+DHT11
Use model load_ state_ Attributeerror appears when dict(): 'STR' object has no attribute 'copy‘
Use AES encryption - reuse the wisdom of predecessors
Spark small case - RDD, broadcast
[2021] Spatio-Temporal Graph Contrastive Learning
使用model.load_state_dict()时,出现AttributeError: ‘str‘ object has no attribute ‘copy‘
ApplicationContext injection bean
MySQL - index