public void CompressFrame() { var handler = new TcpHandler(); var ctx = new NetContext(delegate { }, handler); IExtensionFactory factory = new PerFrameDeflate(0, false); var extn = factory.CreateExtension("deflate-frame"); var data = Encoding.UTF8.GetBytes("Hello"); var frame = new WebSocketsFrame { OpCode = WebSocketsFrame.OpCodes.Text, Payload = new MemoryStream(data), PayloadLength = data.Length, Reserved1 = false }; var connection = new WebSocketConnection(new IPEndPoint(IPAddress.Loopback, 20000)); var encoded = extn.ApplyOutgoing(ctx, connection, frame).Single(); var ms = new MemoryStream(); encoded.Payload.CopyTo(ms); string hex = BitConverter.ToString(ms.GetBuffer(), 0, (int)ms.Length); Assert.AreEqual("F2-48-CD-C9-C9-07-00", hex); // unrelated decoder extn = PerFrameDeflate.Default.CreateExtension("deflate-frame"); var decoded = extn.ApplyIncoming(ctx, connection, frame).Single(); ms = new MemoryStream(); decoded.Payload.Position = 0; decoded.Payload.CopyTo(ms); string s = Encoding.UTF8.GetString(ms.GetBuffer(), 0, (int)ms.Length); Assert.AreEqual("Hello", s); }
public BaseClient(int _id) { id = _id; tcp = new TcpHandler(); udp = new UdpHandler(); }
private bool CheckForPrevClient(TcpClient prevClient) { TcpHandler.WriteMessage(prevClient, TcpProtocol.CheckForDisconnectSend()); int waitTimeInMillis = 500; bool noResponsePrevClient = false; long startTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; while (prevClient.Available <= 0) { long currentTime = DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond; if (currentTime - startTime >= waitTimeInMillis) { noResponsePrevClient = true; break; } } if (noResponsePrevClient) { return(false); } TcpHandler.ReadMessage(prevClient); return(true); }
private void WindowLoaded(object sender, RoutedEventArgs e) { userNameLabel.Content = _userName; _clientInstance = TcpHandler.GetInstance(); //获取当前登录用户的图标 var imagePath = "pack://application:,,,/images/" + _userName + ".jpg"; var iamgeUri = new Uri(imagePath); try { loginUserImage.Source = new BitmapImage(iamgeUri); } catch { imagePath = "pack://application:,,,/images/user.jpg"; iamgeUri = new Uri(imagePath); loginUserImage.Source = new BitmapImage(iamgeUri); } //获取好友列表 var commond = TcpHelper.PackCommmond(_userName, TcpHelper.TalkCommond.UpdateUserList); _clientInstance.SendMessage(commond); //新建线程接收服务端数据 th1 = new Thread(ReceiveData); th1.Start(); //新建线程,用于更新消息提示 th2 = new Thread(ScanEmptyMsgTip); th2.Start(); }
private Highscore ReadHighscore() { string received = TcpHandler.ReadMessage(client); string data = JObject.Parse(received)["data"].ToString(); Highscore highscore = JsonConvert.DeserializeObject <Highscore>(data); return(highscore); }
private void btn_start_Click(object sender, EventArgs e) { //sql starten derMySqlHandler = new MySqlHandler(); //tcp starten derTcpHandler = new TcpHandler(); }
public void DeflateRoundTrip() { var handler = new TcpHandler(); var ctx = new NetContext(delegate { }, handler); var extn = PerFrameDeflate.Default.CreateExtension("deflate-frame"); var conn = new WebSocketConnection(new IPEndPoint(IPAddress.Loopback, 20000)); string[] messages = { "This extension uses one reserved bit to indicate whether DEFLATE is applied to the frame or not. We call this \"COMP\" bit.", "Hello", "This extension operates only on data frames, and only on the \"Application data\" therein (it does not affect the \"Extension data\" portion of the \"Payload data\").", "world", "Hello", "To send a frame with DEFLATE applied, an endpoint MUST use the following algorithm.", "world", "Apply DEFLATE [RFC1951] to all the octets in the \"Application data\" part of the frame. Multiple blocks MAY be used. Any type of block MAY be used. Both block with \"BFINAL\" set to 0 and 1 MAY be used.", "If the resulting data does not end with an empty block with no compression (\"BTYPE\" set to 0), append an empty block with no compression to the tail.", "Remove 4 octets (that are 0x00 0x00 0xff 0xff) from the tail.", "Hello", "Build a frame by putting the resulting octets in the \"Application data\" part instead of the original octets. The payload length field of the frame MUST be the sum of the size of the \"Extension data\" part and these resulting octets. \"COMP\" bit MUST be set to 1." }; var frames = Array.ConvertAll(messages, CreateFrame); int initialSize = frames.Sum(x => x.PayloadLength); Assert.IsTrue(frames.All(x => !x.Reserved1), "no COMP initially"); var munged = frames.SelectMany(f => extn.ApplyOutgoing(ctx, conn, f)).ToArray(); Assert.AreEqual(frames.Length, munged.Length, "compress: 1 in, 1 out"); Assert.IsTrue(frames.Any(x => x.Reserved1), "some COMP after compress"); Assert.IsTrue(frames.Any(x => !x.Reserved1), "some non-COMP after compress"); for (int i = 0; i < munged.Length; i++) { var ms = new MemoryStream(); munged[i].Payload.Position = 0; munged[i].Payload.CopyTo(ms); ms.Position = 0; munged[i].Payload = new MemoryStream(ms.ToArray()); // read-only, deliberately } int mungedSize = frames.Sum(x => x.PayloadLength); var unmunged = munged.SelectMany(f => extn.ApplyIncoming(ctx, conn, f)).ToArray(); Assert.AreEqual(unmunged.Length, unmunged.Length, "inflate: 1 in, 1 out"); Assert.IsTrue(unmunged.All(x => !x.Reserved1), "no COMP after inflate"); int unmungedSize = unmunged.Sum(x => x.PayloadLength); Console.WriteLine("Uncompressed: {0} bytes; compressed: {1} bytes; inflated {2} bytes", initialSize, mungedSize, unmungedSize); string[] finalMessages = Array.ConvertAll(unmunged, ReadFrameMessage); Assert.IsTrue(finalMessages.SequenceEqual(messages), "Equal messages"); }
private Tuple <int, GameData> ReadId() { string received = TcpHandler.ReadMessage(client); JObject jObject = JObject.Parse(received); string data = (string)jObject["data"]; GameData gameData = JsonConvert.DeserializeObject <GameData>(data); return(Tuple.Create((int)jObject["id"], gameData)); }
public void ApplyConfiguration() { var activityMonitor = new ActivityMonitor(); var tcpHandlerConfiguration = new TcpHandlerConfiguration(); var tcpHandler = new TcpHandler(tcpHandlerConfiguration); // ApplyConfiguration should always return false for now. Need to think about its implication before implementing. tcpHandler.ApplyConfiguration(activityMonitor, tcpHandlerConfiguration).Should().BeFalse(); }
public NetManager() { buffer = new ByteBuffer(); tcpConsumer = new SocketDataConsumer(); socket = new SocketClient(); tcpHandler = new TcpHandler(tcpConsumer); socket.init(Configuration.tcpHost, Configuration.tcpPort, tcpHandler); //listener = new DefaultSocketListener(tcpConsumer); }
public void TestExceptionCaught() { var mockLogger = new Mock <ILogger <TcpHandler> >(); var context = new Mock <IChannelHandlerContext>(); var handler = new TcpHandler(mockLogger.Object); handler.ChannelReadComplete(context.Object); handler.ExceptionCaught(context.Object, new Exception("tEST")); }
public void Stop() { AssetLoader.Clear(); GameScheduler.Tasks.Clear(); Events.Clear(); GameThread.Stop(); TcpHandler?.Stop(); Running = false; }
public SmartLockTcpHandlerManager() { SmartLockMap = new Dictionary <string, FSmartLockPair>(); var app_handler = TcpHandler.CreateTcpHandler <TcpHandler_App>(); app_handler.Init(7000, IPAddress.Any); var sl_handler = TcpHandler.CreateTcpHandler <TcpHandler_SmartLock>(); sl_handler.Init(8000, IPAddress.Any); }
public TcpNETServer(IParamsTcpServer parameters, TcpHandler handler = null) { _parameters = parameters; _connectionManager = new TcpConnectionManager(); _handler = handler ?? new TcpHandler(_parameters); _handler.ConnectionEvent += OnConnectionEvent; _handler.MessageEvent += OnMessageEventAsync; _handler.ErrorEvent += OnErrorEvent; _handler.ServerEvent += OnServerEvent; }
static void Main(string[] args) { agent = new Agent47(); var handler = new TcpHandler(port: 0); Agency.RegisterAgent("47", agent, handler); Console.WriteLine("Agent 47 is on his way."); Console.WriteLine($"Access port: {handler.ServerPort}"); Console.ReadLine(); Console.WriteLine($"Current Weapon: {agent.Weapon}"); Console.ReadLine(); }
public JObject Read() { try { return(JsonConvert.DeserializeObject <dynamic>(TcpHandler.ReadMessage(client))); } catch (Exception e) { Console.WriteLine("Exception"); Disconnected = true; return(null); } }
private GameData ReadData() { string received = TcpHandler.ReadMessage(client); JObject jObject = JObject.Parse(received); string data = (string)jObject["data"]; GameData gameData = JsonConvert.DeserializeObject <GameData>(data); // Fix bodies because for some reason it parses with an extra 0,0 coord in the beginning foreach (Snake snake in gameData.Snakes) { snake.Body.RemoveFirst(); } return(gameData); }
public TcpNETServerAuth(IParamsTcpServerAuth parameters, IUserService <T> userService, TcpHandler handler = null) { _parameters = parameters; _userService = userService; _connectionManager = new TcpConnectionManagerAuth <T>(); _handler = handler ?? new TcpHandler(_parameters); _handler.ConnectionEvent += OnConnectionEvent; _handler.MessageEvent += OnMessageEventAsync; _handler.ErrorEvent += OnErrorEvent; _handler.ServerEvent += OnServerEvent; }
public TcpNETServer(IParamsTcpServer parameters, byte[] certificate, string certificatePassword, TcpHandler handler = null) { _parameters = parameters; _connectionManager = new TcpConnectionManager(); _handler = handler ?? new TcpHandler(_parameters, certificate, certificatePassword); _handler.ConnectionEvent += OnConnectionEvent; _handler.MessageEvent += OnMessageEventAsync; _handler.ErrorEvent += OnErrorEvent; _handler.ServerEvent += OnServerEvent; }
private bool ReadEndGame() { string message = TcpHandler.ReadMessage(client); JObject jObject = JObject.Parse(message); string command = (string)jObject["command"]; switch (command) { case "tick/send": return(false); case "end/send": return(true); } return(false); }
// mainly for tests to make sure everything gets cleaned up public void Stop() { AssetLoader.Clear(); GameScheduler.Tasks.Clear(); Events.Clear(); GameThread?.Stop(); TcpHandler?.Stop(); Running = false; Server.Map.Chunks = new Dictionary <string, ServerChunk>(); foreach (var player in Players.ToList()) { player.Tcp.Stop(); } Players.Clear(); PacketsToProccess.Clear(); }
public TcpNETServerAuth(IParamsTcpServerAuth parameters, IUserService <T> userService, byte[] certificate, string certificatePassword, TcpHandler handler = null, TcpConnectionManagerAuth <T> connectionManager = null) { _parameters = parameters; _userService = userService; _connectionManager = connectionManager ?? new TcpConnectionManagerAuth <T>(); _handler = handler ?? new TcpHandler(_parameters, certificate, certificatePassword); _handler.ConnectionEvent += OnConnectionEvent; _handler.MessageEvent += OnMessageEventAsync; _handler.ErrorEvent += OnErrorEvent; _handler.ServerEvent += OnServerEvent; }
private string ProxySummary(TcpHandler control) { StringBuilder summary = new StringBuilder(); lock (control.SocketList) foreach (TcpConnect connect in control.SocketList) { if (connect.State == TcpState.Connected && (connect.Proxy == ProxyType.ClientBlocked || connect.Proxy == ProxyType.ClientNAT) && Instance.Internet.UserNames.ContainsKey(connect.UserID)) { summary.Append(Instance.Internet.UserNames[connect.UserID] + ", "); } } return(summary.ToString()); }
public DhtNetwork(OpCore core, bool lookup) { Core = core; IsLookup = lookup; Cache = new OpCache(this); // lookup config loads cache entries if (IsLookup) { Core.Context.LookupConfig.Load(this); Lookup = Core.Context.LookupConfig; } Local = new DhtClient(); Local.UserID = IsLookup ? Lookup.Ports.UserID : Utilities.KeytoID(Core.User.Settings.KeyPublic); Local.ClientID = (ushort)Core.RndGen.Next(1, ushort.MaxValue); OpID = Utilities.KeytoID(IsLookup ? LookupKey : Core.User.Settings.OpKey); OpCrypt = new RijndaelManaged(); // load encryption if (IsLookup) { OpCrypt.Key = LookupKey; } else { OpCrypt.Key = Core.User.Settings.OpKey; } LocalAugmentedKey = GetAugmentedKey(Local.UserID); Protocol = new G2Protocol(); TcpControl = new TcpHandler(this); UdpControl = new UdpHandler(this); LanControl = new LanHandler(this); RudpControl = new RudpHandler(this); LightComm = new LightCommHandler(this); UPnPControl = new UPnPHandler(this); Routing = new DhtRouting(this); Store = new DhtStore(this); Searches = new DhtSearchControl(this); }
/// <summary> /// 登录连接到服务器 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void loginButton_Click(object sender, RoutedEventArgs e) { //获取服务器IP var serverIP = serverIPTextBox.Text; if (string.IsNullOrEmpty(serverIP)) { MessageBox.Show("请填写正确的服务器地址"); return; } try { var serverIPs = serverIP.Split(':'); TcpHandler._serverHostName = serverIPs[0]; ToString(); TcpHandler._serverPort = System.Convert.ToInt32(serverIPs[1]); }catch (Exception ex) { MessageBox.Show("服务器地址格式不正确"); return; } var userName = userNameTextBox.Text; if (string.IsNullOrEmpty(userName)) { MessageBox.Show("请输入用户名"); return; } try { clientInstance = TcpHandler.GetInstance(); var sendMsg = TcpHelper.PackCommmond(userName, TcpHelper.TalkCommond.Login); //发送登录命令 clientInstance.SendMessage(sendMsg); //创建新线程接收服务端消息 Thread th = new Thread(ReceiveData); th.Start(); }catch (Exception ex) { MessageBox.Show(ex.Message); } }
public MainWindow() { Dispatcher.UnhandledException += Dispatcher_UnhandledException; AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;; GamepadHandler = new GamepadHandler(); GamepadHandler.ConnectionChange += GamepadConnected_Changed; InputSerialDeviceHandler = new SerialDeviceHandler(OSRRemoteDeviceMode.In); InputSerialDeviceHandler.ConnectionChange += SerialConnected_Changed; OutputSerialDeviceHandler = new SerialDeviceHandler(OSRRemoteDeviceMode.Out); OutputSerialDeviceHandler.ConnectionChange += SerialConnected_Changed; SerialPorts = OutputSerialDeviceHandler.GetPorts(); BLEDevices = new ObservableCollection <DeviceModel>(); InputTcpAddresshandler = new TcpHandler(OSRRemoteDeviceMode.In); InputTcpAddresshandler.ConnectionChange += NetworkConnected_Changed; OutputTcpAddresshandler = new TcpHandler(OSRRemoteDeviceMode.Out); OutputTcpAddresshandler.ConnectionChange += NetworkConnected_Changed; InputUdpAddresshandler = new UdpHandler(OSRRemoteDeviceMode.In); InputUdpAddresshandler.ConnectionChange += NetworkConnected_Changed; OutputUdpAddresshandler = new UdpHandler(OSRRemoteDeviceMode.Out); OutputUdpAddresshandler.ConnectionChange += NetworkConnected_Changed; //BLEDeviceHandler = new BLEDeviceHandler(OSRRemoteDeviceMode.Out); //BLEDeviceHandler.ConnectionChange += BLEDeviceHandler_ConnectionChanged; //BLEDeviceHandler.DeviceAdded += BLEDeviceAdded; //BLEDeviceHandler.DeviceRemoved += BLEDeviceRemoved; InitializeComponent(); this.DataContext = this; IPAddressLabel.Content = GetLocalIPV4Address(); RestoreSavedSettings(); _outputNetworkAddressTxtDebouncer = new Debouncer(); _outputNetworkAddressTxtDebouncer.Idled += OutputNetworkAddressTxtDebouncer_Idled; _inputNetworkPortTxtDebouncer = new Debouncer(); _inputNetworkPortTxtDebouncer.Idled += InputNetworkPortTxtDebouncer_Idled; //BLERdo.Checked += OutRadio_Checked; }
static string DecompressFrame(IExtension extn, params byte[] data) { var handler = new TcpHandler(); var ctx = new NetContext(delegate { }, handler); if (extn == null) { extn = PerFrameDeflate.Default.CreateExtension("deflate-frame"); } var frame = new WebSocketsFrame { OpCode = WebSocketsFrame.OpCodes.Text, Payload = new MemoryStream(data), PayloadLength = data.Length, Reserved1 = true }; var connection = new WebSocketConnection(new IPEndPoint(IPAddress.Loopback, 20000)); var decoded = extn.ApplyIncoming(ctx, connection, frame).Single(); return(ReadFrameMessage(decoded)); }
public void StartGame() { IPAddress ip = IPAddress.Parse("127.0.0.1"); // IPAddress ip = IPAddress.Parse("145.49.59.202"); client = new TcpClient(ip.ToString(), 6963); while (client.Available <= 0) { if (Disconnected) { Console.WriteLine(""); return; } } string received = TcpHandler.ReadMessage(client); JObject jObject = JObject.Parse(received); string command = (string)jObject["command"]; Tuple <int, GameData> tuple; if (command != "disconnect/send") { tuple = Tuple.Create((int)jObject["id"], JsonConvert.DeserializeObject <GameData>((string)jObject["data"])); } else { TcpHandler.WriteMessage(client, new JObject()); tuple = ReadId(); } SendName(); id = tuple.Item1; Disconnected = false; gameData = tuple.Item2; draw.GameData = gameData; }
private void WindowLoaded(object sender, RoutedEventArgs e) { talkToNameLabel.Content = _talktoUserName; _clientInstance = TcpHandler.GetInstance(); //获取聊天对象的图标头像 var imagePath = "pack://application:,,,/images/" + _talktoUserName + ".jpg"; var iamgeUri = new Uri(imagePath); try { talkToUserImage.Source = new BitmapImage(iamgeUri); } catch { imagePath = "pack://application:,,,/images/user.jpg"; iamgeUri = new Uri(imagePath); talkToUserImage.Source = new BitmapImage(iamgeUri); } //创建新线程用于读取聊天消息 _readMessageTh = new Thread(ReadMessageList); _readMessageTh.Start(); }
public Task Start() { logger.Debug("TcpReceiver::Start()"); if (state != ReceiverState.Initialized) { throw new InvalidOperationException("Invalid state " + state); } return(Task.Run(() => { state = ReceiverState.Running; try { logger.Debug("TcpReceiver thread started..."); byte[] buf = new byte[16256]; var tcpHanlder = new TcpHandler(); while (state == ReceiverState.Running) { int bytesReceived = socket.Receive(buf, SocketFlags.None); if (bytesReceived > 0) { var frames = tcpHanlder.ProcessData(buf, bytesReceived, session); if (frames != null && frames.Count > 0) { foreach (var frame in frames) { var rtpData = frame.Data; RtpPacket rtpPacket = RtpPacket.Create(rtpData, rtpData.Length, session); if (rtpPacket != null) { OnRtpPacketReceived(rtpPacket); } } } } } } catch (ObjectDisposedException) { logger.Warn("RtpTcpReceiver::ObjectDisposedException"); } catch (Exception ex) { bool socketAborted = false; var socketException = ex as SocketException; if (socketException != null) { var code = socketException.SocketErrorCode; if (code == SocketError.ConnectionAborted || code == SocketError.ConnectionReset || code == SocketError.Interrupted) { logger.Warn("Socket closed: " + code); socketAborted = true; } } if (!socketAborted) { logger.Error(ex); } } finally { Close(); logger.Debug("TcpReceiver thread stopped..."); } })); }