当前位置:网站首页>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
边栏推荐
- 深度学习笔记 —— 微调
- Sword finger offer: the median in the data stream (priority queue large top heap small top heap leetcode 295)
- Informatics Aosai yibentong 1212: letters | openjudge 2.5 156: Letters
- What is the meaning of load balancing
- TypeError: ‘Collection‘ object is not callable. If you meant to call the ......
- 跨境电商 | Facebook 和 Instagram:哪个社交媒体更适合你?
- Unity攝像頭跟隨鼠標旋轉
- MySQL - index
- Teach you how to build the ruoyi system by Tencent cloud
- js 判断数字字符串中是否含有字符
猜你喜欢
拼了!两所A级大学,六所B级大学,纷纷撤销软件工程硕士点!
Pixel 5 5g unlocking tutorial (including unlocking BL, installing edxposed and root)
Learning Android V from scratch - UI
深度学习笔记 —— 物体检测和数据集 + 锚框
Learning Android II from scratch - activity
Painless upgrade of pixel series
Learning Android from scratch -- Introduction
Thoughts on a small program
View, modify and delete [database] table
[2022 ICLR] Pyraformer: Low-Complexity Pyramidal Attention for Long-Range 时空序列建模和预测
随机推荐
Excel protects worksheets and workbooks from damage
深度学习笔记 —— 数据增广
No such file or directory problem while executing shell
The unity camera rotates with the mouse
退出vim的方法
用LCR表完美测试无线充电系统中的线圈
Innovation training (XII) reptile
JS engine loop mechanism: synchronous, asynchronous, event loop
Sword finger offer: the median in the data stream (priority queue large top heap small top heap leetcode 295)
Gets all dates between two times
Alibaba tip: it is better to create threads manually
Spark case - wordcount
使用model.load_state_dict()时,出现AttributeError: ‘str‘ object has no attribute ‘copy‘
Spark small case - RDD, spark SQL
Informatics Olympiad 1955: [11noip popularization group] Swiss round | openjudge 4.1 4363: Swiss round | Luogu p1309 [noip2011 popularization group] Swiss round
List remove an element
Details related to fingerprint payment
Arduino UNO r3+LCD1602+DHT11
What are the redis data types
[winui3] write an imitation Explorer file manager