private void DoSend(byte[] data, Protocal type = Protocal.Tcp) { //SafeDebug.Log("Sending some shit 1"); if (type == Protocal.Tcp || !udpStarted) { //SafeDebug.Log("Sending some shit 2"); if (tcpClient != null && tcpSocket != null) { //if ((ServerCMD)data[0] != ServerCMD.Ping) // SafeDebug.Log("SENDING: " + (ServerCMD)data[0]); data = BufferUtils.AddLength(data); //SafeDebug.Log("Sending some shit 3"); tcpSocket.Send(data); } else { SafeDebug.LogError("Client TCP socket null!"); } } else { if (udpClient != null) { byte[] udpIdBuff = BitConverter.GetBytes((UInt16)UdpID); byte[] buffer = BufferUtils.Add(udpIdBuff, data); udpClient.Send(buffer, buffer.Length); } else { DoSend(data); } } }
public void Send(byte[] data, Protocal type = Protocal.Tcp) { if (!Connected) { return; } try { if (type == Protocal.Tcp || !UdpEnabled) { if (_stream != null && data != null) { _stream.SendMessasge(data); } } else { _server.SendUdp(data, UdpEndPoint); } } catch (IOException) { Close(false, "Send IOException"); } catch (SocketException) { Close(false, "Send SocketException"); } catch (Exception ex) { Logger.LogError("{0}: {1}\n{2}", ex.GetType(), ex.Message, ex.StackTrace); } }
public void Send(string user, byte[] data, Protocal type = Protocal.Tcp) { if (PlayerExists(user)) { _connectedUsers[user].Send(data, type); } }
public void CreateInit(string strIP, int nIP, System.Object objExtend = null) { _strIP = strIP; _socketPool = new ShortSocketPool(); _listener = new KKBaseListener(msgQueue, MsgFactory.Lobby); _protocal = new KKBaseProtocal(); }
/** * 构造 */ public USocket(SocketListner listner, Protocal protocal) { this.listner = listner; this.protocal = protocal; buf = new ByteBuf(4096); //queue = new BlockingQueue<ByteBuf>(5000); }
public void AddEvent(Protocal id, ByteBuffer data) { lock (lockobj) { sEvents.Enqueue(new KeyValuePair <Protocal, ByteBuffer>(id, data)); } }
public void Send(string[] users, byte command, byte[] data, Protocal type = Protocal.Tcp) { for (int i = 0; i < users.Length; i++) { Send(users[i], command, data, type); } }
public Data(Protocal type, byte cmd, byte[] data) { Type = type; command = cmd; buffer = data; Input = Encoding.UTF8.GetString(Buffer); }
protected void CallMethod(Protocal protocal, ByteBuffer buffer) { if (func == null) { func = LuaEnvSingleton.Instance.Global.GetInPath <FDelegate>("Network.OnReceiveMessageQueue"); } func(protocal, buffer); }
/// <summary> /// 填充数据 /// </summary> void FillInfo(ref NetDataWriter dw, Protocal protocal, NPCView npcView) { dw.Reset(); dw.Put((ushort)protocal); dw.Put(npcView.npcId); dw.Put(npcView.position); dw.Put(Quaternion.identity); }
private void HandleDesktopLogin(byte[] message) { short length = BitConverter.ToInt16(message, 0); string msg = Encoding.UTF8.GetString(message, 2, length); //msg = this.DecryptDesktop(msg, "FORGEREMOTETIVITY"); byte[] bs = new byte[1]; //Server.s.Log(msg); if (msg.StartsWith(Protocal.ToString())) //TODO: make a better checker { msg = msg.Replace(string.Format("{0}: ", Protocal), string.Empty); } else { bs[0] = 3; SendData(0x40, bs); Server.s.Log("[Remote] A remote tried to connect with a different version."); return; } if (RemoteServer.tries >= 3) { bs[0] = 4; SendData(0x40, bs); Server.s.Log("[Remote] A remote tried to connect with exceeding incorrect credentials"); return; } if (RemoteServer.tries == 6) { bs[0] = 5; SendData(0x40, bs); Server.s.Log("[Remote] Remote was locked from the console, type \"/remote tryreset\" to reset the try count"); return; } if (HandleLogin(msg)) { bs[0] = 1; if (OnRemoteLogin != null) { OnRemoteLogin(this); } SendData(0x40, bs); Server.s.Log("[Remote] Remote Verified, passing controls to it!"); LoggedIn = true; if (Remotes != null) { Remotes.Add(this); } RegEvents(); //StartUpDesktop(); return; } bs[0] = 2; SendData(0x40, bs); Server.s.Log("[Remote] A Remote with incorrect information attempted to join."); RemoteServer.tries++; return; }
private void Ping(Protocal type) { if (type == Protocal.Udp && !udpStarted) { return; } // sending "true" to tell server to ping back. Send(255, BufferUtils.AddFirst(0x03, BitConverter.GetBytes(true)), type); }
private void Initial() { m_TotalPrice = 0; m_ItemPath = "item.data"; // 检查更新 if (!File.Exists(m_ItemPath)) { File.WriteAllLines(m_ItemPath, new string[] { "0"//版本号 }); } var ft = File.OpenText(m_ItemPath); byte[] buffer = new byte[1024]; Tools.AddToBytes(buffer, 0, (int)Protocal.Check); Tools.AddToBytes(buffer, 4, int.Parse(ft.ReadLine())); ft.Close(); m_Socket.Send(buffer); // 检查版本号 m_Socket.Receive(buffer); Protocal type = (Protocal)Tools.BytesToInt32(buffer, 0); switch (type) { case Protocal.UpdateBegin: { int fsize = Tools.BytesToInt32(buffer, 4); int times = Tools.BytesToInt32(buffer, 8); var fw = File.OpenWrite(m_ItemPath); m_Socket.Receive(buffer); while (--times != 0) { fw.Write(buffer, 8, 1016); m_Socket.Receive(buffer); } fw.Write(buffer, 8, fsize % 1016); fw.Close(); } break; } // 装载货物列表 m_Items = new List <Item>(); ft = File.OpenText(m_ItemPath); ft.ReadLine(); while (!ft.EndOfStream) { m_Items.Add(new Item( int.Parse(ft.ReadLine()), ft.ReadLine(), int.Parse(ft.ReadLine()), int.Parse(ft.ReadLine()), int.Parse(ft.ReadLine()) )); } ft.Close(); }
/// <summary> /// 丢失链接 /// </summary> void OnDisconnected(Protocal protocal, short error, string msg) { Close(); ByteBuffer buffer = new ByteBuffer(); buffer.WriteShort(error); buffer.WriteString(msg); NetworkManager.AddEvent((int)protocal, new ByteBuffer(buffer.ToBytes())); buffer.Close(); }
public void CreateInit(string strIP, int nPort, System.Object objExtend = null) { _strIP = strIP; _nPort = nPort; _listener = new KKBaseListener(msgQueue, MsgFactory.Room); _protocal = new KKBaseProtocal(); _socket = new USocket(_listener, _protocal); _socket.Connect(_strIP, nPort); }
private void HandleMobileLogin(byte[] message) { short length = util.EndianBitConverter.Big.ToInt16(message, 0); string msg = Encoding.UTF8.GetString(message, 2, length); msg = DecryptMobile(msg, "FORGEREMOTETIVITY"); byte[] bs = new byte[1]; //Server.s.Log(msg); if (msg.StartsWith(Protocal.ToString())) //TODO: make a better checker { msg = msg.Replace(string.Format("{0}: ", Protocal), ""); } else { bs[0] = 0x3; SendData(0xb, bs); Server.s.Log("[Remote] A remote tried to connect with a different version."); } if (RemoteServer.tries >= 0x3) { bs[0] = 0x4; SendData(0xb, bs); Server.s.Log("[Remote] A remote tried to connect with exceeding incorrect credentials"); } if (RemoteServer.tries == 0x6) { bs[0] = 0x5; SendData(0xb, bs); Server.s.Log("[Remote] Remote was locked from the console, type \"/remote tryreset\" to reset the try count"); } if (HandleLogin(msg)) { bs[0] = 1; if (OnRemoteLogin != null) { OnRemoteLogin(this); } SendData(11, bs); GenerateKeyMobile(_keyMobile); Server.s.Log("[Remote] Remote Verified, passing controls to it!"); LoggedIn = true; Remotes.Add(this); regMobileEvents(); } else { bs[0] = 0x2; SendData(11, bs); Server.s.Log("[Remote] A Remote with incorrect information attempted to join."); RemoteServer.tries++; } }
/// <summary> /// 发送数据 /// </summary> /// <param name="protocal"></param> /// <param name="buffer"></param> public void SendData(Protocal protocal, NetDataWriter buffer = null) { if (mClient != null) { lock (msgLock) { var packet = objMgr.Get <PacketData>(); packet.protocal = protocal; packet.writer = buffer; mPacketPool.Enqueue(packet); } } }
/// <summary> /// 处理数据 /// </summary> public void DispatchMessage(NetPeer peer, NetDataReader reader) { var messageid = reader.GetUShort(); Protocal key = (Protocal)messageid; if (mHandlers.ContainsKey(key)) { mHandlers[key].OnMessage(peer, reader); } else { mDefaultHandler.OnMessage(peer, reader); } }
/// <summary> /// 消息接收 /// </summary> public void OnReceived(NetPeer peer, NetDataReader reader) { IMessageHandler handler = null; Protocal key = (Protocal)reader.GetUShort(); if (mHandlers.ContainsKey(key)) { handler = mHandlers[key]; } else { handler = mDefaultHandler; } handler.OnMessage(peer, reader); }
public void OnRecvData(WebSocket socket, WebSocketHandler handler, JsonData message) { var commandId = message["CommandId"].ToString(); Protocal key = (Protocal)int.Parse(commandId); logger.Info("ReceiveAsync[message.CommandId]:" + key); if (mHandlers.ContainsKey(key)) { mHandlers[key].OnMessage(socket, handler, message); } else { mHandlers[Protocal.Default].OnMessage(socket, handler, message); } }
private void ProcessReceiveBuffer(byte[] buffer, Protocal type) { timeOutWatch.Reset(); timeOutWatch.Start(); if (buffer.Length > 0) { byte command = buffer[0]; buffer = BufferUtils.RemoveFront(BufferUtils.Remove.CMD, buffer); Data data = new Data(type, command, buffer); _server.Process(this, data); } else { Logger.Log("{1}: Received empty buffer!", type.ToString()); } }
/// <summary> /// 分发给各个客户端通信的线程 /// </summary> private void ReceiveThread(object socket) { Socket clientSocket = (Socket)socket; string name = ""; byte[] buffer = new byte[1024]; while (clientSocket.Connected) { int length = clientSocket.Receive(buffer); Protocal ptl = (Protocal)Tools.BytesToInt32(buffer, 0); switch (ptl) { case Protocal.Sale: { int itemID = Tools.BytesToInt32(buffer, 4); foreach (var item in m_Items) { if (item.id == itemID) { item.saleCount += Tools.BytesToInt32(buffer, 8); break; } } } break; case Protocal.Check: Check(clientSocket, buffer, name); break; case Protocal.UpdateBegin: break; case Protocal.Update: break; case Protocal.UpdateEnd: break; case Protocal.Same: break; case Protocal.Login: Login(clientSocket, in buffer, out name); break; } } }
/// <summary> /// 数据接收 /// </summary> public void OnRequestReceived(ClientSession session, BinaryRequestInfo requestInfo) { ByteBuffer buffer = new ByteBuffer(requestInfo.Body); int commandId = buffer.ReadShort(); Protocal c = (Protocal)commandId; string className = "SimpleFramework.Message." + c; Console.WriteLine("OnRequestReceived--->>>" + className); Type t = Type.GetType(className); IMessage obj = (IMessage)Activator.CreateInstance(t); if (obj != null) { obj.OnMessage(session, buffer); } obj = null; t = null; //释放内存 }
private void Send(byte[] data, Protocal type = Protocal.Tcp) { if ((data.Length + 2) >= 65536) { SafeDebug.LogError(string.Format("Send data length exceeds 65,536: {0} - {1}", data.Length + 2, BitConverter.ToString(data, 0, 4))); return; } if (Thread.CurrentThread == mainThread) { Loom.QueueAsyncTask("Net", () => { DoSend(data, type); }); } else { DoSend(data, type); } }
private void Process(byte[] data, Protocal type) { byte command = data[0]; byte[] dst = BufferUtils.RemoveFront(BufferUtils.Remove.CMD, data); if (CommandExists(command)) { Loom.QueueOnMainThread(() => commands[command](new Data(type, command, dst))); /*if (Commands[command].Async) * Commands[command].Cmd(new Data(type, command, dst)); * else * { * TaskQueue.QueueMain(() => Commands[command].Cmd(new Data(type, command, dst))); * }*/ } //Traffic traffic = new Traffic((OpCodes)command, dst); //ProcessData(traffic, type); }
/// <summary> /// 发送消息 /// </summary> public static void SendMessage(ClientSession session, Protocal protocal, ByteBuffer buffer) { byte[] message = buffer.ToBytes(); using (MemoryStream ms = new MemoryStream()) { ms.Position = 0; BinaryWriter writer = new BinaryWriter(ms); ushort protocalId = (ushort)protocal; ushort msglen = (ushort)(message.Length + 2); writer.Write(msglen); writer.Write(protocalId); writer.Write(message); writer.Flush(); if (session != null && session.Connected) { byte[] payload = ms.ToArray(); session.Send(payload, 0, payload.Length); } else { Console.WriteLine("client.connected----->>false"); } } }
public Boolean DownloadSharingFile(Protocal.SharingInfo si) { String copyRef = si.Reference; String fileName = si.FileName; try { String dropboxPath = BaseExtension.FileStringHelper.GetNonConflictFileName( Path.Combine( DropBoxController.DropBox_DownloadFolder , fileName ) ); UserKey uk = PreKeyring.UserKey; PRE_KEY userKey = new PRE_KEY(); userKey.PK.PK1 = uk.PK1; userKey.PK.PK2 = uk.PK2; userKey.SK.X1 = uk.SK1; userKey.SK.X2 = uk.SK2; PRE_Cipher CKey = new PRE_Cipher(); CKey.E = si.CKey_E; CKey.F = si.CKey_F; CKey.U = si.CKey_U; CKey.W = si.CKey_W; String key = ProxyReEncryption.KeyDecrypt( userKey , CKey ); FileMetaData fi = new FileMetaData(); fi.FileName = fileName; fi.FilePath = this.dropBoxController.DropboxSecuruStikFolder2SecuruStikFolder( dropboxPath ); fi.Key = key; fi.PlainTextHash = ""; fi.CryptTextHash = ""; PreKeyring.FileInfo_Update( fi ); String dropboxRemotePath = this.dropBoxController.SecuruStikFolder2RemoteDropboxPath( fi.FilePath ); this.dropBoxController.CopyAsync( copyRef , dropboxRemotePath ); } catch ( System.Exception ex ) { log.ErrorFormat("DownloadSharingFile {0}", si.FileName, ex); PreKeyring.SharingFile_Delete( si.Reference ); return false; } return true; }
public USocket NewSocket(SocketListner listener, Protocal protocal) { ShortUSocket socket = null; if (_lstPool.Count == 0) { socket = new ShortUSocket(listener, protocal); socket.ID = _nIDIndex++; Debug.Log("<color=cyan>" + "创建" + socket.ID + "号Socket" + "</color>"); } else { socket = _lstPool.Dequeue(); socket.setLister(listener); socket.setProtocal(protocal); Debug.Log("<color=cyan>" + "直接使用" + socket.ID + "号Socket" + "</color>"); } socket.IsInPool = false; socket._actionClose = OnShortSocketClose; return(socket); }
public static bool TryParse(Protocal protocal, byte[] data, out TorqueEventArgs args) { args = null; try { switch (protocal) { case Protocal.OpenProtocal: args = ParseOpenProtocal(data); return true; default: return false; } } catch { return false; } }
/** * 构造 */ public USocket(SocketListner listner, Protocal protocal) { this.listner = listner; this.protocal = protocal; buf = new ByteBuf(4096); }
/** * 装入一个协议解析器 */ public void setProtocal(Protocal p) { this.protocal = p; }
/** * 构造 */ public USocket(SocketListner listner,Protocal protocal) { this.listner = listner; this.protocal = protocal; }
/// <summary> /// Called when a socket user pings the server. /// </summary> /// <param name="user">Socket user who sent ping.</param> /// <param name="protocal">Protocal ping was sent with.</param> /// <param name="pingBack">Whether a response was sent back the user.</param> public virtual void UserPinged(SocketUser user, Protocal protocal, bool pingBack) { }