internal void RegisterHandlerSafe(short msgType, JHSNetworkMessageDelegate handler)
        {
            if (handler == null)
            {
                if (NetConfig.logFilter >= JHSLogFilter.Error)
                {
                    JHSDebug.LogError("RegisterHandlerSafe id:" + msgType + " handler is null");
                }
                return;
            }

            if (NetConfig.logFilter >= JHSLogFilter.Developer)
            {
                JHSDebug.Log("RegisterHandlerSafe id:" + msgType + " handler:" + handler.GetMethodName());
            }
            if (m_MsgHandlers.ContainsKey(msgType))
            {
                if (NetConfig.logFilter >= JHSLogFilter.Error)
                {
                    JHSDebug.LogError("RegisterHandlerSafe id:" + msgType + " handler:" + handler.GetMethodName() + " conflict");
                }
                return;
            }
            m_MsgHandlers.Add(msgType, handler);
        }
Esempio n. 2
0
        public void StartConnect()
        {
            IPAddress ipAddress = IPAddress.Parse(IP);

            remoteEP = new IPEndPoint(ipAddress, Port);

            if (connection != null && !connection.m_Disposed)
            {
                connection.Dispose();
                connection = null;
            }

            connection = new JHSConnection();
            connection.Init(true);

            if (NetConfig.logFilter >= JHSLogFilter.Developer)
            {
                JHSDebug.Log("JHSNetworkManager Connecting to Server reconnect attmpt:" + m_RecconectTry);
            }
            connection.m_socket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp)
            {
                Blocking = false
            };
            connection.m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveBuffer, 1048576);
            connection.m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendBuffer, 1048576);
            connection.m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, 1);
            connection.m_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 0);
            connection.m_socket.BeginConnect(remoteEP, ConnectCallback, connection.m_socket);
            Connecting        = true;
            PermaDisconnected = false;
        }
Esempio n. 3
0
        public void StartListening()
        {
            IPAddress  ipAddress     = IPAddress.Parse(NetConfig.IP);
            IPEndPoint localEndPoint = new IPEndPoint(ipAddress, NetConfig.Port);

            _receiveSocket = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                _receiveSocket.Bind(localEndPoint);
                _receiveSocket.Listen(100);
                if (NetConfig.logFilter >= JHSLogFilter.Developer)
                {
                    JHSDebug.Log("JHSNetworkServer :: Started to listen :" + ipAddress.ToString() + " Port:" + NetConfig.Port + " Protocol Version:" + NetConfig.Version);
                }
                else
                {
                    JHSDebug.Log("Server Started IP[" + ipAddress.ToString() + ":" + NetConfig.Port + "] Version:[" + NetConfig.Version + "]");
                }
                _receiveSocket.BeginAccept(new AsyncCallback(AcceptCallback), _receiveSocket);
            }
            catch (Exception e)
            {
                if (NetConfig.logFilter >= JHSLogFilter.Developer)
                {
                    JHSDebug.LogError("JHSNetworkServer :: Excepiton:" + e.ToString());
                }
            }
        }
Esempio n. 4
0
 protected void BeginSend()
 {
     if (ToSend.Count == 0)
     {
         sendbegined = false;
         return;
     }
     try
     {
         SendState state;
         lock (ToSend)
         {
             state = ToSend.Dequeue();
         }
         byte[] buf = Crypt.Encode(PacketFarmer.ToBytes(state.msgType, state.packet));
         m_socket.BeginSend(buf, 0, buf.Length, SocketFlags.None, asyncsend, null);
     }
     catch (ObjectDisposedException)
     {
         // do nothing
     }
     catch (SocketException)
     {
         Disconnect();
     }
     catch (Exception e)
     {
         if (NetConfig.logFilter >= JHSLogFilter.Error)
         {
             JHSDebug.LogError("JHSConnection :: Exception: " + e.ToString());
         }
         Disconnect();
     }
 }
Esempio n. 5
0
 private void EndSend(IAsyncResult ar)
 {
     try
     {
         int bytesSent = m_socket.EndSend(ar);
         if (NetConfig.UseStatistics)
         {
             BytesSent   += bytesSent;
             PacketsSend += 1;
             lastSentTime = JHSTime.Time;
         }
         BeginSend();
         if (NetConfig.logFilter >= JHSLogFilter.Developer)
         {
             JHSDebug.Log(string.Format("JHSConnection :: Sent {0} bytes.", bytesSent));
         }
     }
     catch (ObjectDisposedException)
     {
         // do nothing
     }
     catch (SocketException)
     {
         Disconnect();
     }
     catch (Exception e)
     {
         if (NetConfig.logFilter >= JHSLogFilter.Error)
         {
             JHSDebug.LogError("JHSConnection :: Exception: " + e.ToString());
         }
         Disconnect();
     }
 }
Esempio n. 6
0
        public void DoUpdate()
        {
            if (Connecting)
            {
                return;
            }

            if (PermaDisconnected)
            {
                return;
            }

            if (!Connected)
            {
                if (LastTryToConnect > JHSTime.Time)
                {
                    return;
                }

                if (RecconectTry > m_RecconectTry)
                {
                    LastTryToConnect = JHSTime.Time + NetConfig.ReconnectTimeOut;
                    m_RecconectTry++;
                    StartClient();
                }
                else
                {
                    if (NetConfig.logFilter >= JHSLogFilter.Developer)
                    {
                        JHSDebug.Log("JHSProtocol Could not connect to the server.");
                    }
                    PermaDisconnected = true;
                }
            }
        }
        private void WriteCheckForSpace(ushort count)
        {
            if (Position + count < m_Buffer.Length)
            {
                return;
            }

            int newLen = (int)Math.Ceiling(m_Buffer.Length * k_GrowthFactor);

            while (Position + count >= newLen)
            {
                newLen = (int)Math.Ceiling(newLen * k_GrowthFactor);
                if (newLen > k_BufferSizeWarning)
                {
                    if (NetConfig.logFilter >= JHSLogFilter.Warning)
                    {
                        JHSDebug.LogWarning("JHSNetworkBuffer :: Size is " + newLen + " bytes!");
                    }
                }
            }

            // only do the copy once, even if newLen is increased multiple times
            byte[] tmp = new byte[newLen];
            m_Buffer.CopyTo(tmp, 0);
            m_Buffer = tmp;
        }
Esempio n. 8
0
 internal void AddConnection(JHSConnection con)
 {
     Connected(con);
     if (NetConfig.logFilter >= JHSLogFilter.Developer)
     {
         JHSDebug.Log("JHSNetworkManager :: Added Connection To Pool.");
     }
 }
Esempio n. 9
0
        private void ConnectCallback(IAsyncResult ar)
        {
            Socket client = (Socket)ar.AsyncState;

            try
            {
                client.EndConnect(ar);
            }
            catch (SocketException x)
            {
                if (connection != null)
                {
                    connection.Disconnect();
                }
                if (NetConfig.logFilter >= JHSLogFilter.Developer)
                {
                    JHSDebug.Log("JHSNetworkManager :: Excepiton:" + x.GetErrorCode());
                }
                Connecting = false;
                return;
            }

            catch (Exception e)
            {
                if (connection != null)
                {
                    connection.Disconnect();
                }
                if (NetConfig.logFilter >= JHSLogFilter.Developer)
                {
                    JHSDebug.Log("JHSNetworkManager :: Excepiton:" + e.ToString());
                }
                Connecting = false;
                return;
            }
            try
            {
                connection.SetHandlers(m_MessageHandlers);
                connection.StartReceiving(client);
                HandShakeMsg packet = new HandShakeMsg
                {
                    Version = NetConfig.Version,
                    OP      = 0,
                };
                connection.Send(InternalMessages.HeandShake_Server, packet);
                Connecting     = false;
                Connected      = true;
                m_RecconectTry = 0;
            }
            catch (Exception e)
            {
                if (NetConfig.logFilter >= JHSLogFilter.Developer)
                {
                    JHSDebug.Log("JHSNetworkManager :: Excepiton:" + e.ToString());
                }
                Connecting = false;
            }
        }
Esempio n. 10
0
        private void EndReceive(IAsyncResult result)
        {
            if (stage == PerStage.NotConnected)
            {
                return;
            }
            lock (m_lockread)
            {
                try
                {
                    int len = m_socket.EndReceive(result);
                    if (len == 0)
                    {
                        Disconnect(); return;
                    }

                    byte[] buf = Crypt.Decode(this.m_Connbuffer, len);
                    for (int i = 0; i < buf.Length; i++)
                    {
                        JHSNetworkReader ds = PacketFarmer.Accumulate(buf[i]);
                        if (ds != null)
                        {
                            if (HandleReader(ds))
                            {
                                if (NetConfig.UseStatistics)
                                {
                                    PacketsRec += 1;
                                    BitesRev   += len;
                                }
                            }
                        }
                    }
                    m_socket.BeginReceive(this.m_Connbuffer, 0, this.m_Connbuffer.Length, SocketFlags.None, asyncrec, null);
                }
                catch (ObjectDisposedException)
                {
                    // do nothing
                }
                catch (SocketException sk)
                {
                    if (NetConfig.logFilter >= JHSLogFilter.Developer)
                    {
                        JHSDebug.LogError("JHSConnection :: Excepiton:" + sk.GetErrorCode());
                    }
                    Disconnect();
                }
                catch (Exception ex)
                {
                    if (NetConfig.logFilter >= JHSLogFilter.Developer)
                    {
                        JHSDebug.LogError("JHSConnection :: Excepiton:" + ex.ToString());
                    }
                    Disconnect();
                }
            }
        }
 internal void Discconnectx(JHSConnection con)
 {
     if (m_activeTransport != null)
     {
         m_activeTransport.Disconnect(con);
         if (NetConfig.logFilter >= JHSLogFilter.Log && con != null)
         {
             JHSDebug.Log("JHSNetworkManager :: Disconnected :" + con.connectionId);
         }
     }
 }
 internal void InternalSend(short msgType, JHSMessageBase msg)
 {
     if (m_activeTransport != null)
     {
         m_activeTransport.Send(0, msgType, msg);
         return;
     }
     if (NetConfig.logFilter >= JHSLogFilter.Error)
     {
         JHSDebug.LogError("JHSNetworkManager :: Failed to send message to connection ID '" + 0 + ", not found in connection list");
     }
 }
 public void Write(byte[] buffer, int offset, int count)
 {
     if (count > UInt16.MaxValue)
     {
         if (NetConfig.logFilter >= JHSLogFilter.Error)
         {
             JHSDebug.LogError("JHSNetworkWriter :: Write: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes.");
         }
         return;
     }
     m_Buffer.WriteBytesAtOffset(buffer, (ushort)offset, (ushort)count);
 }
Esempio n. 14
0
 public void Send(uint connectionId, short msgType, JHSMessageBase msg)
 {
     if (connection != null && connection.ConnectionReady())
     {
         connection.Send(msgType, msg);
         return;
     }
     if (NetConfig.logFilter >= JHSLogFilter.Error)
     {
         JHSDebug.LogError("JHSNetworkManager :: CLIENT BASE TRANSPORT Failed to send message to connection ID '" + connectionId + ", not found in connection list");
     }
 }
Esempio n. 15
0
 public JHSConnection StartClient()
 {
     if (NetConfig.logFilter >= JHSLogFilter.Log)
     {
         JHSDebug.Log("JHSNetworkManager :: Created Client Version:" + NetConfig.Version);
     }
     Connecting = true;
     IP         = NetConfig.IP;
     Port       = NetConfig.Port;
     StartConnect();
     Connected = false;
     return(null);
 }
Esempio n. 16
0
 public void Send(uint connectionId, short msgType, JHSMessageBase msg)
 {
     if (m_Connections.TryGetValue(connectionId, out JHSConnection conection))
     {
         if (conection != null)
         {
             conection.Send(msgType, msg);
             return;
         }
     }
     if (NetConfig.logFilter >= JHSLogFilter.Error)
     {
         JHSDebug.LogError("JHSNetworkServer :: Failed to send message to connection ID '" + connectionId + ", not found in connection list");
     }
 }
 //NOTE: this will write the entire buffer.. including trailing empty space!
 public void WriteBytesFull(byte[] buffer)
 {
     if (buffer == null)
     {
         Write((UInt16)0);
         return;
     }
     if (buffer.Length > UInt16.MaxValue)
     {
         if (NetConfig.logFilter >= JHSLogFilter.Error)
         {
             JHSDebug.LogError("JHSNetworkWriter :: WriteBytes: buffer is too large (" + buffer.Length + ") bytes. The maximum buffer size is 64K bytes.");
         }
         return;
     }
     Write((UInt16)buffer.Length);
     m_Buffer.WriteBytes(buffer, (UInt16)buffer.Length);
 }
 public byte[] ToBytes(short msgType, JHSMessageBase packet)
 {
     lock (m_Writer)
     {
         m_Writer.StartMessage(msgType);
         packet.Serialize(m_Writer);
         m_Writer.FinishMessage();
         byte[]      buf     = m_Writer.ToArray();
         List <byte> listbuf = new List <byte>();
         listbuf.AddRange(Write(PACKAGE_HEADER_ID));
         listbuf.AddRange(Write((ushort)buf.Length));
         listbuf.AddRange(buf);
         byte[] nesent = listbuf.ToArray();
         if (NetConfig.logFilter >= JHSLogFilter.Developer)
         {
             JHSDebug.Log("JHSPacketFarmer Write:" + BitConverter.ToString(nesent));
         }
         return(nesent);
     }
 }
        public void WriteBytesAndSize(byte[] buffer, int count)
        {
            if (buffer == null || count == 0)
            {
                Write((UInt16)0);
                return;
            }

            if (count > UInt16.MaxValue)
            {
                if (NetConfig.logFilter >= JHSLogFilter.Error)
                {
                    JHSDebug.LogError("JHSNetworkWriter :: WriteBytesAndSize: buffer is too large (" + count + ") bytes. The maximum buffer size is 64K bytes.");
                }
                return;
            }

            Write((UInt16)count);
            m_Buffer.WriteBytes(buffer, (UInt16)count);
        }
Esempio n. 20
0
        private static void TESTMSG_RECIVE(JHSNetworkMessage netMsg)
        {
            uint        connectionId = netMsg.conn.connectionId;
            string      ip           = netMsg.conn.IP;
            SearchMatch packet       = netMsg.ReadMessage <SearchMatch>();

            if (packet != null)
            {
                JHSDebug.Log(packet.op.ToString());
                netMsg.conn.Send(100, new SearchMatch()
                {
                    op = SearchMatchOperations.Search
                });
                netMsg.conn.Send(100, new SearchMatch()
                {
                    op = SearchMatchOperations.START, IP = "127.0.0.1", port = 1985
                });

                //  JHSNetworkManager.SendToAll(100, new TESTMSGRE() {ClientId = connectionId, Time = packet.Time, TimeServ = JHSTime.TimeStamp });
            }
        }
Esempio n. 21
0
 public void SendToAll(short msgType, JHSMessageBase msg)
 {
     try
     {
         JHSConnection[] connections = m_Connections.Values.ToArray();
         for (int i = 0; i < connections.Length; i++)
         {
             if (connections[i] != null && connections[i].ConnectionReady())
             {
                 connections[i].Send(msgType, msg);
             }
         }
     }
     catch (Exception e)
     {
         if (NetConfig.logFilter >= JHSLogFilter.Error)
         {
             JHSDebug.LogError("JHSNetworkServer :: Exception:" + e.ToString());
         }
     }
 }
        public JHSNetworkReader Accumulate(byte bt)
        {
            btbuf.Add(bt);
            if (btbuf.Count < PACKAGE_HEADER_LEN)
            {
                return(null);
            }

            byte[] buff = btbuf.ToArray();
            uint   head = ReadUInt32(buff, 0);
            uint   len  = ReadUInt16(buff, 4);
            int    ptr  = btbuf.Count - PACKAGE_HEADER_LEN;

            if (head == PACKAGE_HEADER_ID)
            {
                if (btbuf.Count >= 65536)
                {
                    btbuf.Clear();
                    return(null);
                }

                if (len == ptr)
                {
                    if (NetConfig.logFilter >= JHSLogFilter.Developer)
                    {
                        JHSDebug.Log("JHSPacketFarmer Read:" + BitConverter.ToString(buff));
                    }

                    btbuf.Clear();
                    var x = new JHSNetworkReader(buff);
                    x.ReadBytes(PACKAGE_HEADER_LEN);
                    return(x);
                }
            }

            return(null);
        }
Esempio n. 23
0
 protected bool HandleReader(JHSNetworkReader reader)
 {
     try
     {
         ushort sz        = reader.ReadUInt16();
         short  msgType   = reader.ReadInt16();
         byte[] msgBuffer = reader.ReadBytes(sz);
         if (isClient)
         {
             JHSNetworkReader msgReader = new JHSNetworkReader(msgBuffer);
             if (m_MessageHandlersDict.ContainsKey(msgType))
             {
                 JHSNetworkClient.PushMessage(new JHSNetworkMessage()
                 {
                     msgType = msgType,
                     reader  = msgReader,
                     conn    = this
                 });
             }
             else
             {
                 if (NetConfig.logFilter >= JHSLogFilter.Error)
                 {
                     JHSDebug.LogError("JHSConnection :: Unknown message ID " + msgType + " connId:" + connectionId);
                 }
                 if (NetConfig.UseStatistics)
                 {
                     ReadError += 1;
                 }
             }
         }
         else
         {
             JHSNetworkReader          msgReader   = new JHSNetworkReader(msgBuffer);
             JHSNetworkMessageDelegate msgDelegate = null;
             if (m_MessageHandlersDict.ContainsKey(msgType))
             {
                 msgDelegate = m_MessageHandlersDict[msgType];
             }
             if (msgDelegate != null)
             {
                 msgDelegate(new JHSNetworkMessage()
                 {
                     msgType = msgType,
                     reader  = msgReader,
                     conn    = this
                 });
             }
             else
             {
                 if (NetConfig.logFilter >= JHSLogFilter.Error)
                 {
                     JHSDebug.LogError("JHSConnection :: Unknown message ID " + msgType + " connId:" + connectionId);
                 }
                 if (NetConfig.UseStatistics)
                 {
                     ReadError += 1;
                 }
             }
         }
     }
     catch { }
     return(true);
 }
Esempio n. 24
0
        internal void HandleServerHandShake(JHSNetworkMessage netMsg)
        {
            HandShakeMsg packet = netMsg.ReadMessage <HandShakeMsg>();

            if (packet != null)
            {
                if (packet.OP == 0) //VER VERSION
                {
                    if (packet.Version == NetConfig.Version)
                    {
                        netMsg.conn.stage = PerStage.Verifying;
                        HandShakeMsg p = new HandShakeMsg
                        {
                            Version = netMsg.conn.connectionId,
                            OP      = 0
                        };
                        netMsg.conn.Send(InternalMessages.HeandShake_Client, p);
                    }
                    else
                    {
                        netMsg.conn.Disconnect();
                    }
                }
                else if (packet.OP == 1)
                {
                    if (packet.Version == NetConfig.Key)
                    {
                        netMsg.conn.stage = PerStage.Connecting;
                        HandShakeMsg p = new HandShakeMsg
                        {
                            Version = (uint)NetConfig.Key,
                            OP      = 1
                        };
                        netMsg.conn.Send(InternalMessages.HeandShake_Client, p);
                    }
                    else
                    {
                        netMsg.conn.Disconnect();
                    }
                }
                else if (packet.OP == 2)
                {
                    if (packet.Version == NetConfig.Key)
                    {
                        netMsg.conn.stage = PerStage.Connected;
                        if (NetConfig.logFilter >= JHSLogFilter.Log)
                        {
                            JHSDebug.Log("JHSNetworkManager :: Connected:" + netMsg.conn.connectionId);
                        }
                        AddConnection(netMsg.conn);
                    }
                    else
                    {
                        netMsg.conn.Disconnect();
                    }
                }
                else
                {
                    netMsg.conn.Disconnect();
                }
            }
        }