public void Receive() { WebSocketClient ws = new WebSocketClient(new Uri("ws://localhost:8080/YASO/chat")); ManualResetEvent receiveEvent = new ManualResetEvent(false); ws.OnMessage += (s, e) => { receiveEvent.Set(); }; ws.Connect(); ws.Send("login: User1"); bool received = receiveEvent.WaitOne(TimeSpan.FromSeconds(2)); Assert.IsTrue(received); receiveEvent.Close(); ws.Close(); }
public void UsageTest() { var resetEvent = new ManualResetEvent(false); var location = new Uri("ws://echo.websocket.org"); var client = new WebSocketClient(location); client.OnOpen = () => Debug.WriteLine("Connection Open"); client.OnClose = () => { Debug.WriteLine("Connection Closed"); resetEvent.Set(); }; client.OnError = _ => Debug.WriteLine("error " + _); client.OnMessage = m => { Debug.WriteLine(m); client.CloseAsync(); }; client.Connect(); client.Send("Hello!"); resetEvent.WaitOne(); }
public virtual void Connect(bool isRetry) { lock (lockerObj) { if (IsConnecting && !isRetry) { traceLogger.Trace("连接中,忽略连接请求"); return; } IsConnecting = true; } Regex regex = new Regex("[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}"); if (regex.IsMatch(IP)) { client.Connect(IPAddress.Parse(IP), Port); } else { client.Connect(IP, Port); } }
private void CreateClient() { DebugUtility.LogTrace(LoggerTags.Online, "¡¾Common¡¿ CreateClient..."); // Create WebSocket instance var ws = new WebSocketClient(); // Add OnOpen event listener ws.onConnected += () => { mConnectedTime = DateTime.Now; DebugUtility.LogTrace(LoggerTags.Online, "¡¾Client¡¿ connected : {0}", mConnectedTime.ToLongTimeString()); DebugUtility.LogTrace(LoggerTags.Online, "¡¾Client¡¿ State : {0}", ws.state); ws.SendMessage(Encoding.UTF8.GetBytes("WebSocketDemo from Unity Client.")); }; // Add OnMessage event listener ws.onRecv += (byte[] msg) => { DebugUtility.LogTrace(LoggerTags.Online, "¡¾Client¡¿ received message: " + Encoding.UTF8.GetString(msg)); ws.Disconnect(); }; // Add OnError event listener ws.onError += (string errMsg) => { DebugUtility.LogTrace(LoggerTags.Online, "¡¾Client¡¿ error: " + errMsg); }; // Add OnClose event listener ws.onDisconnected += (code) => { mDisconnectedTime = DateTime.Now; DebugUtility.LogTrace(LoggerTags.Online, "¡¾Client¡¿ closed with code: {0}, DisconnectedTime : {1}, Alive : {2}(seconds)", code, mDisconnectedTime.ToLongTimeString(), (mDisconnectedTime - mConnectedTime).TotalSeconds); }; // Connect to the server if (createServer) { string url = string.Concat(serverHost, ":", port.ToString(), serverService); DebugUtility.Log(LoggerTags.Online, "¡¾Common¡¿ CreateClient {0}", url); ws.Connect(url); } else { DebugUtility.Log(LoggerTags.Online, "¡¾Common¡¿ CreateClient {0}", host); ws.Connect(host); } mClient = ws; }
private void ConnectToServer() { Console.WriteLine($"In client mode, connecting to {TargetHost}"); var wsc = new WebSocketClient(); wsc.ConnectToUrl($"ws://{TargetHost}/", new string[] { "ludus" }, true); peer = wsc; GetTree().NetworkPeer = peer; //wsc.Connect("connected_to_server", this, nameof(ConnectedToServer)); wsc.Connect("connection_failed", this, nameof(ConnectionFailed)); wsc.Connect("server_disconnected", this, nameof(ServerDisconnected)); }
public async Task <IWebSocketClient> CreateWebSocketClient(string url) { var socket = new WebSocketClient(new MessageInterpreter(new Logger())); await socket.Connect(url); return(socket); }
public async Task ClientReadingTestMethod() { Uri _serverURI = new Uri("http://localhost:8003/ws/"); Uri _clientURI = new Uri("ws://localhost:8003/ws/"); Task _server = RunWebSocketServerWriter(_serverURI); bool _onClose = false; List <string> _messages = new List <string>(); WebSocketConnection _connection = null; await Task.Delay(100); await WebSocketClient.Connect(_clientURI, x => _connection = x, message => _messages.Add(message)); Assert.IsNotNull(_connection); _connection.onMessage = x => _messages.Add(x); bool _onError = false; _connection.onError = () => _onError = true; _connection.onClose = () => _onClose = true; await Task.Delay(200); Assert.AreEqual <int>(11, _messages.Count); Assert.IsTrue(_onClose); await Task.Delay(100); Assert.IsTrue(_server.IsCompleted); Assert.AreEqual <TaskStatus>(TaskStatus.RanToCompletion, _server.Status); Assert.IsFalse(_onError); Assert.AreEqual <int>(11, _messages.Count); }
static async Task MainAsync(string[] args) { using (var client = new WebSocketClient("gateway.discord.gg", 80)) { await client.Connect(); } }
public void Connect() { if (client != null) { client.Connect(); } }
public void Connect() { if (WebSocketClient != null) { WebSocketClient.Connect(); } }
private void button3_Click(object sender, EventArgs e) { //secure websocket if (_client != null) { return; } //------------------------------------------------ _client = new WebSocketClient(); _client.UseSsl = true; _client.SetHandler((req, resp) => { string serverMsg = req.ReadAsString(); //Console.WriteLine(serverMsg); this.Invoke(new MethodInvoker(() => { listBox1.Items.Add(serverMsg); //if (_outputMsgCount < 100) //{ // _client.SendData("LOOPBACK: hello server " + _outputMsgCount++); //} })); }); //_client.Connect("https://localhost:8080/websocket"); //_client.Connect("https://localhost:8080/websocket"); //_client.LoadCertificate("mycert.pfx", "12345"); _client.Connect("https://localhost:8080/"); }
protected void onConnectToggled(object sender, EventArgs e) { ToggleButton connectBtn = sender as ToggleButton; if (connectBtn.Active) { if (createSocket()) { enableWidgets(true); ws.Connect(); connectBtn.Label = "Connected"; } else { connectBtn.Active = false; } } else { enableWidgets(false); if (ws != null) { ws.Disconnect(); } connectBtn.Label = "Connect"; } }
static void Main(string[] args) { System.Threading.Thread.Sleep(1000); var uri = new Uri("ws://localhost:8000/sample"); var handler = new MessageHandler(); var etiquette = new ClientEtiquette(uri, "null", null, new Dictionary <string, string> { { "From", "Client" } }); //var etiquette = new ClientEtiquette(uri, "originTest"); var webSocketClient = new WebSocketClient(uri, etiquette, handler); webSocketClient.Connect(); var messageBus = Configure.Bus .UsingTransport(webSocketClient.WebSocket) .Start(); Console.WriteLine("Client started"); Console.WriteLine("Connecting to " + uri); var text = string.Empty; while ((text = Console.ReadLine()) != "q") { var message = new Message { From = "Client", Text = text }; messageBus.Send(message); } }
private async void Connect(string endpoint) { Debug.Log("Start connecting"); if (m_Client != null) { Debug.LogError("Already has a client, cannot connect"); return; } m_Client = WebSocketClient.Create(endpoint); m_Client.OnOpen += () => { Debug.Log($"OnOpen called on {m_Thread}"); AddToDialogList($"Connected to {endpoint}"); }; m_Client.OnClose += (System.Net.WebSockets.WebSocketCloseStatus closeStatus) => { Debug.Log($"OnClose called with closeStatus {closeStatus} on {m_Thread}"); AddToDialogList($"Disconnected from {endpoint}"); }; m_Client.OnMessage += (byte[] message) => { Debug.Log($"OnMessage called on {m_Thread}"); AddToDialogList(System.Text.Encoding.UTF8.GetString(message)); }; m_Client.OnError += (string error) => { Debug.Log($"OnError called on {m_Thread}"); AddToDialogList(error); }; await m_Client.Connect(); Debug.Log($"Connected! on {m_Thread}"); }
public void Connect() { _nextPing = null; _activityTimeout = 0; this.AddInfoLog(LocalizedStrings.Connecting); _client.Connect("wss://ws.bitstamp.net", true); }
void Start() { stageDango = StageDango.GetComponent <StageDango>(); stageBottle = StageBottle.GetComponent <StageBottle>(); stageSakura = StageSakura.GetComponent <StageSakura>(); websocketClient.Connect(); websocketClient.Send("Connect"); }
public WebSocketController(Repository repository) { this.repository = repository; webSocketClient = new WebSocketClient(); _ = webSocketClient.Connect(URI); webSocketClient.onMessage = new Action <string>(receiveMessage); }
public void Connect() { try { wsc.Port = port; wsc.URL = host; resultCodes = wsc.Connect(); if (debug > 0) { CrestronConsole.Print("\n Websocket resultCodes: " + resultCodes.ToString()); } if (resultCodes == (int)WebSocketClient.WEBSOCKET_RESULT_CODES.WEBSOCKET_CLIENT_SUCCESS) { CrestronConsole.PrintLine("\n Websocket Connect WEBSOCKET_CLIENT_SUCCESS: " + host + ":" + port.ToString()); keepAliveMessageReceived = false; keepAliveCounter = 0; keepAliveReconnect = false; keepAliveTimerRepeatTime = 5000; keepAliveTimer.Reset(1000, keepAliveTimerRepeatTime); if (debug > 0) { CrestronConsole.PrintLine("\n Websocket connected."); } resultCodes = wsc.ReceiveAsync(); if (debug > 0) { CrestronConsole.Print("\n Websocket ReceiveAsync resultCodes: " + resultCodes.ToString()); } } else if (resultCodes.ToString().Contains("WEBSOCKET_CLIENT_ALREADY_CONNECTED")) { if (debug > 0) { CrestronConsole.Print("\n Websocket re-initialize..."); } wsc.Disconnect(); } else { if (debug > 0) { CrestronConsole.Print("\n Websocket could not connect to server. Connect return code: " + resultCodes.ToString()); } Disconnect(); } } catch (Exception e) { if (debug > 0) { CrestronConsole.Print("\n Websocket Connect exception: " + e.Message); } Disconnect(); } }
private async System.Threading.Tasks.Task ConnectAsync(int portNumber) { Uri _uri = new Uri($@"ws://localhost:{portNumber}/"); WebSocketConnection socketConnection = await WebSocketClient.Connect(_uri, LogToConsole); socketConnection.onMessage = LogToConsole; this.api = new API(socketConnection); this.api.GetReportSender(); }
/// <summary> /// Method to connect to Twitch's PubSub service. You MUST listen toOnConnected event and listen to a Topic within 15 seconds of connecting (or be disconnected) /// </summary> public void Connect() { socket = WebSocketClient.Create(new Uri("wss://pubsub-edge.twitch.tv")); socket.OnConnected += Socket_OnConnected; socket.OnError += OnError; socket.OnMessage += OnMessage; socket.OnDisconnected += Socket_OnDisconnected; socket.Connect(); }
public override async Task <bool> Run() { this.Info($"Host:{Arguments.Host} Start rollBack from version:" + Arguments.DeployFolderName); HttpRequestClient httpRequestClient = new HttpRequestClient(); httpRequestClient.SetFieldValue("publishType", "windowservice_rollback"); httpRequestClient.SetFieldValue("id", Arguments.LoggerId); httpRequestClient.SetFieldValue("serviceName", Arguments.ServiceName); httpRequestClient.SetFieldValue("deployFolderName", Arguments.DeployFolderName); httpRequestClient.SetFieldValue("Token", Arguments.Token); HttpLogger HttpLogger = new HttpLogger { Key = Arguments.LoggerId, Url = $"http://{Arguments.Host}/logger?key=" + Arguments.LoggerId }; var isSuccess = true; WebSocketClient webSocket = new WebSocketClient(this.Log, HttpLogger); try { var hostKey = await webSocket.Connect($"ws://{Arguments.Host}/socket"); httpRequestClient.SetFieldValue("wsKey", hostKey); var uploadResult = await httpRequestClient.Upload($"http://{Arguments.Host}/rollback", null, GetProxy()); webSocket.ReceiveHttpAction(true); if (webSocket.HasError) { isSuccess = false; this.Error($"Host:{Arguments.Host},Rollback Fail,Skip to Next"); } else { if (uploadResult.Item1) { this.Info($"【rollback success】Host:{Arguments.Host},Response:{uploadResult.Item2}"); } else { isSuccess = false; this.Error($"Host:{Arguments.Host},Response:{uploadResult.Item2},Skip to Next"); } } } catch (Exception ex) { isSuccess = false; this.Error($"Fail Rollback,Host:{Arguments.Host},Response:{ex.Message},Skip to Next"); } finally { await webSocket?.Dispose(); } return(await Task.FromResult(isSuccess)); }
static void Main(string[] args) { Console.WriteLine("test no...\r\n0\r\n1"); //------------------------------------------------ WebSocketClient _client = null; string line = Console.ReadLine(); int count = 0; while (line != null) { if (int.TryParse(line, out int line_count)) { if (line_count == 0) { if (_client == null) { _client = new WebSocketClient(); _client.UseSsl = true; //test send-recv with defalte compression //client request this value but server may not accept the req compression _client.Compression = WebSocketContentCompression.Gzip; _client.SetHandler((req, resp) => { string serverMsg = req.ReadAsString(); Console.WriteLine(serverMsg); }); _client.Connect("https://localhost:8080/websocket"); //------------------------------------------------ Console.WriteLine("connected!"); } else { Console.WriteLine("already connected!"); } } else if (line_count > 0 && line_count <= 5000) { byte[] binaryData = System.Text.Encoding.UTF8.GetBytes("abcde"); for (int i = 0; i < line_count; ++i) { //_client.SendData("A" + (count++)); _client.SendBinaryData(binaryData); } } else { Console.WriteLine("input between 0-5000"); } } line = Console.ReadLine(); } }
public void ConnectToPeers(Uri[] newPeers) { List <Task> _connectionJobs = new List <Task>(); foreach (Uri peer in newPeers) { _connectionJobs.Add(WebSocketClient.Connect(peer, async ws => await InitConnectionAsync(ws), Log)); } Task.WaitAll(_connectionJobs.ToArray()); }
public void connect() { Console.WriteLine("Will connect to GraphWalker server..."); ws = new WebSocketClient("ws://localhost:8887/") { OnReceive = OnReceive, OnConnected = OnConnected }; ws.Connect(); }
public void ConnectTest() { //string url = BinanceDexEnvironment.TEST_NET.WsBaseUrl; //string url = "wss://testnet-dex.binance.org/api/ws/$all@blockheight"; WebSocketClient client = new WebSocketClient(); client.Env = BinanceDexEnvironment.TEST_NET; client.Topic = ETopic.Blockheight; client.StreamData += Client_StreamData; client.Connect(); }
public int connect() { try { ret = ws_client.Connect(); if (ret == (int)WebSocketClient.WEBSOCKET_RESULT_CODES.WEBSOCKET_CLIENT_SUCCESS) { CrestronConsole.Print("[WSClient.connect] websocket connected"); } else { CrestronConsole.PrintLine("[WSClient.connect] websocket could not connect, err: {0}" + ret.ToString()); } } catch (Exception ex) { CrestronConsole.PrintLine("[WSClient.connect] exception : {0}", ex.ToString()); } return((int)ret); }
// virtual methods public override void _Ready() { chatLog = FindNode("ChatLog") as RichTextLabel; inputLabel = FindNode("ChatGroup") as Label; inputField = FindNode("ChatInput") as LineEdit; inputField.Connect("text_entered", this, nameof(_ChatInputEntered)); ChangeGroup(0); ws.Connect("connection_closed", this, nameof(_ConnectionClosed)); ws.Connect("connection_error", this, nameof(_ConnectionClosed)); ws.Connect("connection_established", this, nameof(_ConnectionEstablished)); ws.Connect("data_received", this, nameof(_OnDataReceived)); // Initiate connection to the given URL. var err = ws.ConnectToUrl(websocketUrl); if (err != Error.Ok) { GD.Print("Unable to connect"); } }
// connects to WebSocket after handshake private void send_connect() { if (websocketConnectionUp) { Debug.Print("connect uri: " + socketioURI); websocketClient.Connect(socketioURI); } else { throw new Exception("Connection not UP!"); } }
private void ConnectInternal(string address, int port) { string scheme = UseSecureClient ? "wss://" : "ws://"; Uri uri = new System.UriBuilder(scheme, address, port, "game").Uri; if (Mirror.LogFilter.Debug) { Debug.Log("attempting to start client on: " + uri.ToString()); } ClientInterface = new WebSocketClient(uri); ClientInterface.Connect(); }
protected override void OnStart(string[] args) { try { string wsServer = ConfigurationManager.AppSettings["ws-server"]; string stanox = ConfigurationManager.AppSettings["stanox"]; if (string.IsNullOrEmpty(wsServer) || string.IsNullOrEmpty(stanox)) { throw new ArgumentNullException("", "both ws-server and stanox must be set in app.config"); } _statistics = Delays.Load(); if (_statistics.Created.Date < DateTime.Now.Date) { const string start = "Early Departures for {0:dd-MM-yy}:"; var statsByMinute = _statistics.EarlyDepartures.GroupBy(v => v); ICollection <string> values = new List <string>(statsByMinute.Count()); const string format = "{0} mins early:{1}"; foreach (var minutes in statsByMinute) { values.Add(string.Format(format, minutes.Key, minutes.Count())); } SendTweet(string.Concat(string.Format(start, _statistics.Created), string.Join(",", values.ToArray()))); _statistics = Delays.NewInstance(); _statistics.Save(); } double lat, lng; if (double.TryParse(ConfigurationManager.AppSettings["Lat"], out lat) && double.TryParse(ConfigurationManager.AppSettings["Lng"], out lng)) { Latitude = lat; Longitude = lng; } Trace.TraceInformation("Connecting to server on {0}", wsServer); _wsClient = new WebSocketClient(wsServer) { OnReceive = OnReceive, OnDisconnect = OnDisconnect }; _wsClient.Connect(); Trace.TraceInformation("Subscribing to stanox {0}", stanox); _wsClient.Send(string.Format("substanox:{0}", stanox)); } catch (Exception e) { Trace.TraceError("Error starting service: {0}", e); throw; } }
IEnumerator ConnectCoroutine() { yield return(webSocket.Connect()); Debug.Log("Connected"); var handshake = new Message() { Type = MessageType.HandShake, Body = new ClientHandShakeMessage() { Type = HandShakeType.Join, Name = PlayerName, } }; webSocket.SendMessage(JsonConvert.SerializeObject(handshake)); Debug.Log("Handshake sent"); yield return(webSocket.WaitMessage()); Debug.Log(webSocket.Data); var response = (JsonConvert.DeserializeObject <Message>(webSocket.Data).Body as JObject).ToObject <ServerHandShakeMessage>(); PlayerID = response.ID; RoomID = response.RoomID; Ready = true; // Get records var request = new WWW($"http://{host}/get-records/{RoomID}", new byte[] { 0 }); yield return(request); Debug.Log(request.text); var records = JsonConvert.DeserializeObject <PlayerRecord[]>(request.text); foreach (var record in records) { var player = GameSystem.Instance.SpawnPlayBackPlayer(PlaybackPlayerPrefab, SpawnLocation, record.Records.Select(r => new ControlDetail() { Action = (PlayerAction)r.Control.Action, Tick = r.Tick, Direction = r.Control.Direction }).ToArray()); Players[record.ID] = player; } yield return(webSocket.WaitMessage()); var sync = (JsonConvert.DeserializeObject <Message>(webSocket.Data).Body as JObject).ToObject <SyncMessage>(); StartCoroutine(GameLoopCoroutine()); }
static void Main(string[] args) { var client = new TcpClient("10.101.101.3", 5900); var tcpStream = client.GetStream(); Rebex.Licensing.Key = "==AXMSijet0GjA68FiQeAvp4dhPxXsTVD/4uNj+PG/nAxY=="; var ws = new WebSocketClient(); ws.Settings.SslAcceptAllCertificates = true; ws.Connect("wss://websocketvnc.northeurope.cloudapp.azure.com/ws"); var pipe = new Pipe(tcpStream, ws); pipe.TunnelAsync(); }
public void StressTest1() { var waitEvent = new AutoResetEvent(false); var server = new WebSocketServer(8080); server.OnReceive += Receive; server.Start(); WebSocketClient socket = new WebSocketClient("ws://localhost:8080/"); socket.Connect(); countdownEvent = new CountdownEvent(Messages); for (var i = 0; i < Messages; i++) ThreadPool.QueueUserWorkItem(DoSend, socket); countdownEvent.Wait(new TimeSpan(0, 0, 120)); Assert.AreEqual(0, countdownEvent.CurrentCount); }
public void Connect() { WebSocketClient ws = new WebSocketClient(new Uri("ws://localhost:8080/YASO/chat")); ws.Connect(); ws.Close(); }
public void SendAndRecieve() { WebSocketClient ws = new WebSocketClient(new Uri("ws://localhost:8080/YASO/chat")); ManualResetEvent receiveEvent = new ManualResetEvent(false); ws.OnMessage += (s, e) => { receiveEvent.Set(); }; ws.Connect(); ws.Send("login: "******"Msg #" + i); received = receiveEvent.WaitOne(TimeSpan.FromSeconds(2)); Assert.IsTrue(received, "Fail on round " + i); } receiveEvent.Close(); ws.Close(); }
public void Send() { WebSocketClient ws = new WebSocketClient(new Uri("ws://localhost:8080/YASO/chat")); ws.Connect(); ws.Send("login: User1"); ws.Close(); }
static void Main(string[] args) { try { var config = new WebSocketClientConfiguration(); //config.SslTargetHost = "Cowboy"; //config.SslClientCertificates.Add(new System.Security.Cryptography.X509Certificates.X509Certificate2(@"D:\\Cowboy.cer")); //config.SslPolicyErrorsBypassed = true; var uri = new Uri("ws://echo.websocket.org/"); //var uri = new Uri("wss://127.0.0.1:22222/test"); //var uri = new Uri("ws://127.0.0.1:22222/test"); _client = new WebSocketClient(uri, config, _log); _client.ServerConnected += OnServerConnected; _client.ServerDisconnected += OnServerDisconnected; _client.ServerTextReceived += OnServerTextReceived; _client.ServerBinaryReceived += OnServerBinaryReceived; _client.Connect(); Console.WriteLine("WebSocket client has connected to server [{0}].", uri); Console.WriteLine("Type something to send to server..."); while (_client.State == WebSocketState.Open) { try { string text = Console.ReadLine(); if (text == "quit") break; if (text == "many") { text = new string('x', 1024); Stopwatch watch = Stopwatch.StartNew(); int count = 10000; for (int i = 1; i <= count; i++) { _client.SendBinary(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> Sequence[{1}] -> TextLength[{2}].", _client.LocalEndPoint, i, text.Length); } watch.Stop(); Console.WriteLine("Client [{0}] send binary -> Count[{1}] -> Cost[{2}] -> PerSecond[{3}].", _client.LocalEndPoint, count, watch.ElapsedMilliseconds / 1000, count / (watch.ElapsedMilliseconds / 1000)); } else if (text == "big") { text = new string('x', 1024 * 1024 * 100); _client.SendBinary(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); } else { _client.SendBinary(Encoding.UTF8.GetBytes(text)); Console.WriteLine("Client [{0}] send binary -> [{1}].", _client.LocalEndPoint, text); //_client.SendText(text); //Console.WriteLine("Client [{0}] send text -> [{1}].", _client.LocalEndPoint, text); } } catch (Exception ex) { Console.WriteLine(ex.Message); } } _client.Close(WebSocketCloseCode.NormalClosure); Console.WriteLine("WebSocket client has disconnected from server [{0}].", uri); } catch (Exception ex) { Console.WriteLine(ex.Message); } Console.ReadKey(); }