forked from hiram3512/HiSocket
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPackageExample.cs
More file actions
46 lines (44 loc) · 1.5 KB
/
PackageExample.cs
File metadata and controls
46 lines (44 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/***************************************************************
* Description:
*
* Documents: https://github.com/hiramtan/HiSocket
* Author: hiramtan@live.com
***************************************************************/
using HiFramework;
using HiSocket.Tcp;
using System;
namespace HiSocket.Example
{
public class PackageExample:PackageBase
{
protected override void Pack(BlockBuffer<byte> bytes, Action<byte[]> onPacked)
{
//Use int as header
int length = bytes.WritePosition;
var header = BitConverter.GetBytes(length);
var newBytes = new BlockBuffer<byte>(length + header.Length);
//Write header and body to buffer
newBytes.Write(header);
newBytes.Write(bytes.Buffer);
//Notice pack funished
onPacked(newBytes.Buffer);
}
protected override void Unpack(BlockBuffer<byte> bytes, Action<byte[]> onUnpacked)
{
//Because header is int and cost 4 byte
while (bytes.WritePosition > 4)
{
int length = BitConverter.ToInt32(bytes.Buffer, 0);
//If receive body
if (bytes.WritePosition >= 4 + length)
{
bytes.MoveReadPostion(4);
var data = bytes.Read(length);
//Notice unpack finished
onUnpacked(data);
bytes.ResetIndex();
}
}
}
}
}