Giter Club home page Giter Club logo

hisocket's Introduction

HiSocket

It is a lightweight client socket solution, you can used it in Unity3d or C# project

Packagist GitHub release Github Releases


中文说明

How to use

Quick Start:

        //tcp example
        private IPackage package = new PackageExample();
        private TcpConnection tcp;
        void Init()
        {
            tcp = new TcpConnection(package);
            tcp.OnConnected += OnConnected;
            tcp.OnReceive += OnReceive;
            //...
            //...
            tcp.Connect("127.0.0.1",999);
        }
        void OnConnected()
        {
            //connect success
            tcp.Send(new byte[10]);//send message
        }

        void OnReceive(byte[] bytes)
        {
            //get message from server
        }

More example:


General

This project contains:

  • Tcp
    • TcpConnection
    • TcpSocket
    • Plugin
      • Ping
      • Statistical
  • Message
    • Binary Message
    • Protobuf Message
    • Aes encryption
  • BlockBuffer

Features

  • Support Tcp socket
  • Scalable byte Array
  • High-performance byte block buffer
  • Message registration and call back
  • Support byte message
  • Support protobuf message
  • AES encryption

Details

  • Use async connection in main thread(avoid thread blocking).
  • Using Circular_buffer to avoid memory allocation every time, and reduce garbage collection.
  • You can get current connect state and message by adding listener of event.
  • If you use Tcp socket, you should implement IPackage interface to pack or unpack message.
  • Ping: there is a ping plugin you can used, but if you are used in unity3d because of the bug of mono, it will throw an error on .net2.0(.net 4.6 will be fine, also you can use unity's api to get ping time)

Framework

framework

Advanced

  • If you are clear about socket, you also can use TcpSocket to achieve your logic, anyway the recommend is TcpConnection.
  • You can use API get socket and do extra logic, for example modify socket's out time
  • You can use API get send and receive buffer, for example when disconnect, how to handle buffer's data? just clear or resend to server.
  • OnSocketReceive and OnReceive are diffrent, for example OnSocketReceive size is 100 byte, if user do nothing when uppack OnReceive size is 100. but when user do some zip/unzip(encription.etc) OnReceive size is not 100 anymore.
  • You can add many different plugins based on TcpConnection to achieve different functions.
  • There are a message register base class help user to quick register id and callback(based on reflection)
  • The encryption is use AES, if you want to use encryption you can use the API to encrypte your bytes.
  • .etc

Instructions

Tcp provides reliable, ordered, and error-checked delivery of a stream of bytes. you have to split bytes by yourself, in this framework you can implement IPackage interface to achieve this.

Because Tcp is a a stream of bytes protocol, user should split the bytes to get correct message package. when create a tcp socket channel there must be a package instance to pack and unpack message.

Pack and Unpack message: In the beginning we define a packager to split bytes, when send message we add length in the head of every message and when receive message we use this length to get how long our message is.

Udp provides checksums for data integrity, and port numbers for addressing different functions at the source and destination of the datagram. that means you don't know current connect state, but package is integrated.

If use Udp connection shold define send and receive's buffer size.

  • Ping :    Because there is a bug with mono on .net 2.0 and subset in unity3d, you can use logic as below.
    public int PingTime;
    private Ping p;
    private float timeOut = 1;
    private float lastTime;
    void Start()
    {
        StartCoroutine(Ping());
    }
    IEnumerator Ping()
    {
        p = new Ping("127.0.0.1");
        lastTime = Time.realtimeSinceStartup;
        while (!p.isDone && Time.realtimeSinceStartup - lastTime < 1)
        {
            yield return null;
        }
        PingTime = p.time;
        p.DestroyPing();
        yield return new WaitForSeconds(1);
        StartCoroutine(Ping());
    }

Example

There are many example in HiSocketExample project or in HiSocket.unitypackage, here is some of them:

Package 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();
                }
            }
        }
    }
TcpConnection tcp;
        void Connect()
        {
            tcp = new TcpConnection(new PackageExample());
            tcp.OnDisconnected += OnDisconnect;
            tcp.Connect("127.0.0.1", 999);
            tcp.Socket.NoDelay = true;
            tcp.Socket.SendTimeout = 100;
            tcp.Socket.ReceiveTimeout = 200;
            //...


            // you can add plugin sub from IPlugins
            tcp.AddPlugin(new StatisticalPlugin("Statistical"));//this plugin calculate how many send
        }

        void OnDisconnect()
        {
            var length = tcp.SendBuffer.WritePosition;
            Console.WriteLine("Still have {0} not send to server when abnormal shutdown");
            var data = tcp.SendBuffer.Read(length);
            tcp.SendBuffer.ResetIndex();

            //use can handle these data, for example maybe can send next time when connect again
            //tcp.Send(data);
        }
 /// <summary>
    /// The recommend is use TcpConnection 
    /// </summary>
    class Example3
    {
        TcpSocket tcp; //The recommend is use TcpConnection 
        void Connect()
        {
            tcp = new TcpSocket(1024);//set buffer size
            tcp.OnReceiveBytes += OnReceive;
            tcp.Connect("127.0.0.1", 999);
        }

        void OnReceive(byte[] bytes)
        {
            //split bytes here
        }
    }

support: [email protected]


MIT License

Copyright (c) [2017] [Hiram]

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

hisocket's People

Contributors

hiram3512 avatar qingyoucan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hisocket's Issues

OnDisconnected event has problem

hisocket_disconnect_bug

when i close server application, client can not receive the OnDisconnected event.
it seems some thing wrong with TcpSocket.cs on line 268.
when server close, it trigger an exception on line 262, then the TcpSocket catch but throw it away.
thus DisconnectedEvnet() on line 280 will never be invoke.

StringHexToBytes has problem

server received data:
1A 00 00 00 61 75 74 68 65 6E 74 69 63 61 74 65 20 31 0D 0A 6B 69 6C 6C 20 22 31 22 0D 0A
but client send data:
61 75 74 68 65 6E 74 69 63 61 74 65 20 31 0D 0A 6B 69 6C 6C 20 22 31 22 0D 0A

why?

新版本是否有意愿开发Server端的?

你好,很高兴看到你的项目,但我们公司现在考虑用socket架构的server端,是否有考虑在下一个版本中加入Server端?
非常感谢你的项目。

yang

2021-12-03

Support reconnect feature in example

Hi! @hiramtan
I just found this code and it is very simple and easy to understand! Thank so much for such an awesome plugin!
I need implement reconnect feature(when user drop by a weak signal or switch from wifi to Mobile Data)
Please add to example how to do that!
Thank so much!

如果解析失败,数据就被丢弃了。

在TcpSocket中,使用var bytes = ReceiveBuffer.Read(ReceiveBuffer.WritePosition);将数据从缓冲中拿出来送去unpack,但是如果由于网络波动,这次接收的信息并不完整,导致解析失败,那拿出来的这部分数据就会被直接丢弃,并没有放回缓冲区等待后面新的数据来重新解析。

编辑器卡死

第二次运行example场景,必卡死。ondestory 内 DisConnect();tcp.Dispose() 也没用。貌似没别的可用的了。unity2018.2.5

直接在主线程创建TcpConnect 连接 会阻塞主线程

具体原因我也不确定,但现象是我在主线程直接连接服务器,连接之后的代码就不再执行了。
但是我新创建一个线程进行连接的时候,如下代码:

TcpConnection tcp;
        public void Connect()
        {
            tcp = new TcpConnection(new NormalPackage());
            tcp.OnConnected += OnConnected;
            tcp.OnConnecting += OnConnecting;
            tcp.OnDisconnected += OnDisconnect;
            tcp.OnSendBytes += OnSendBytes;
            tcp.OnSendMessage += OnSendMessage;
            tcp.OnReceiveMessage += OnReceiveMessage;
            tcp.OnReceiveBytes += OnReceive;

            tcp.Connect("192.168.0.108", 10402);
            //tcp.Socket.NoDelay = true;
            //tcp.Socket.SendTimeout = 100;
            //tcp.Socket.ReceiveTimeout = 200;

            // you can add plugin sub from IPlugins
            //tcp.AddPlugin(new StatisticalPlugin("Statistical"));//this plugin calculate how many send
        }

        public void Init() {
            Thread thread = new Thread(new ThreadStart(Connect));
           
            thread.Start();
        }

会导致
tcp.Socket.NoDelay = true;会在这里报错
可以请教是什么情况吗?还是我使用姿势不对?

Problema with expections being thrown

Hey @hiram3512 ,

First thanks for the project it really helps me a lot, but i want to ask you something: always when an erro occours the error is thrown but i haven't any way to catch this error, maybe you could change this behavior to trigger an error event instead of thrown an error so i can listen to event and do something.

Thanks

IndexOutOfRangeException: Index was outside the bounds of the array.

IndexOutOfRangeException: Index was outside the bounds of the array.
HiFramework.CircularBuffer`1[T].Write (T[] array) (at Assets/ThirdPlugin/HiSocket/TcpConnection/Socket/CircalBuffer.cs:166)
HiSocket.TcpSocket.Send (System.Byte[] bytes) (at Assets/ThirdPlugin/HiSocket/TcpConnection/Socket/TcpSocket.cs:171)
HiSocket.TcpConnection.m__0 (System.Byte[] x) (at Assets/ThirdPlugin/HiSocket/TcpConnection/TcpConnection.cs:62)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.