public void SendMessage <T>(SprotoTypeBase rpcReq, RpcRspHandler rpcRspHandler = null) { session += 1; if (session >= maxSession) { session = 0; } if (rpcRspHandler != null) { AddHandler(session, rpcRspHandler); } byte[] message = rpcReq.encode(); MemoryStream ms = null; using (ms = new MemoryStream()) { ms.Position = 0; BinaryWriter writer = new BinaryWriter(ms); UInt16 msglen = Util.SwapUInt16((UInt16)(message.Length + 8)); writer.Write(msglen); int tag = protocol[typeof(T)]; sessionDict.Add((long)session, protocol[tag].Response.Value); tag = Util.SwapInt32(tag); writer.Write(tag); writer.Write(message); int swap_session = Util.SwapInt32(session); writer.Write(swap_session); writer.Flush(); byte[] payload = ms.ToArray(); NetworkManager.GetInstance().SendBytesWithoutSize(payload); } }
private static void Send(SprotoTypeBase rpc, long?session, int tag) { if (!bConnected || !Enabled) { return; } package pkg = new package(); pkg.type = tag; if (session != null) { pkg.session = (long)session; sessionDict.Add((long)session, protocol[tag].Response.Value); } sendStream.Seek(0, SeekOrigin.Begin); int len = pkg.encode(sendStream); if (rpc != null) { len += rpc.encode(sendStream); } byte[] data = sendPack.pack(sendStream.Buffer, len); if (data.Length > MAX_PACK_LEN) { Debug.Log("data.Length > " + MAX_PACK_LEN + " => " + data.Length); return; } sendStream.Seek(0, SeekOrigin.Begin); sendStream.WriteByte((byte)(data.Length >> 8)); sendStream.WriteByte((byte)data.Length); sendStream.Write(data, 0, data.Length); try { socket.Send(sendStream.Buffer, sendStream.Position, SocketFlags.None); } catch (Exception e) { Debug.Log("send Lost network" + ((SocketException)e).ErrorCode); Debug.Log("send Lost network" + ((SocketException)e).ToString()); Debug.LogWarning(e.ToString()); } }
public byte[] serialize(SprotoTypeBase sprotoObject, eMessageRequestType messageType) { string messageName = sprotoObject.GetType().Name; int messageNameLen = messageName.Length + 1; byte [] encodedMessage = sprotoObject.encode(); byte [] messageNameBytes = Encoding.ASCII.GetBytes(messageName.ToCharArray()); int totalSize = 3 + messageNameLen + encodedMessage.Length; byte [] sendBuffer = new byte[totalSize]; sendBuffer[0] = (byte)messageType; sendBuffer[1] = (byte)(messageNameLen >> 8); sendBuffer[2] = (byte)(messageNameLen); System.Buffer.BlockCopy(messageNameBytes, 0, sendBuffer, 3, messageName.Length); // Append an extra '\0' sendBuffer[3 + messageName.Length] = 0; System.Buffer.BlockCopy(encodedMessage, 0, sendBuffer, 4 + messageName.Length, encodedMessage.Length); return(sendBuffer); }