public Task Connect(string host, CancellationToken cancelToken) { _webSocket = new WSSharpNWebSocket(host); _webSocket.EmitOnPing = false; _webSocket.EnableRedirection = true; _webSocket.Compression = WebSocketSharp.CompressionMethod.Deflate; _webSocket.SetProxy(_config.ProxyUrl, _config.ProxyCredentials?.UserName, _config.ProxyCredentials?.Password); _webSocket.OnMessage += (s, e) => { if (e.Type == WebSocketSharp.Opcode.Binary) RaiseBinaryMessage(e.RawData); else if (e.Type == WebSocketSharp.Opcode.Text) RaiseTextMessage(e.Data); }; _webSocket.OnError += async (s, e) => { _parent.RaiseOnLog(LogMessageSeverity.Error, e.Exception?.GetBaseException()?.Message ?? e.Message); await _parent.DisconnectInternal(e.Exception, skipAwait: true).ConfigureAwait(false); }; _webSocket.OnClose += async (s, e) => { string code = e.WasClean ? e.Code.ToString() : "Unexpected"; string reason = e.Reason != "" ? e.Reason : "No Reason"; Exception ex = new Exception($"Got Close Message ({code}): {reason}"); await _parent.DisconnectInternal(ex, skipAwait: true).ConfigureAwait(false); }; _webSocket.Log.Output = (e, m) => { }; //Dont let websocket-sharp print to console _webSocket.Connect(); return TaskHelper.CompletedTask; }
public WebSocket(Client client, string name) : base(client, name) { this.socket = new WebSocketSharp.WebSocket (client.GetUrl()); }
public void Connect() { client = new WebSocketSharp.WebSocket(config.EnpointUri); client.WaitTime = new TimeSpan(0, 0, config.KeepAliveInSeconds); client.OnMessage += (sender, e) => { SSAPMessage <SSAPBodyMessage> message = SSAPMessage <SSAPBodyMessage> .FromJson <SSAPBodyMessage>(e.Data); if (message.MessageType != SSAPMessageTypesEnum.INDICATION) { Callback c; callbacks.TryDequeue(out c); c.Handle(e.Data); } else { foreach (IListener4SIBIndicationNotifications listener in subscriptionListeners) { Action a = () => { listener.OnIndication("", message); }; Task.Factory.StartNew(a); } } }; client.Connect(); }
public UniRx.IObservable <Websocket> Connection(Config config) { return(UniRx.Observable.Create <Websocket> (observer => { var impl = new WebSocketSharp.WebSocket(config.url.ToString(), config.protocols); System.EventHandler <WebSocketSharp.ErrorEventArgs> onError = (obj, e) => { observer.OnError(new System.Exception(e.Message)); }; impl.OnError += onError; foreach (var pr in config.coockie) { impl.SetCookie(new WebSocketSharp.Net.Cookie(pr.Key, pr.Value)); } var socket = new Websocket(impl, shared_data); impl.OnOpen += (sender, e) => { impl.OnError -= onError; this.shared_data.connected.Add(socket.GetHashCode(), socket); observer.OnNext(socket); observer.OnCompleted(); }; impl.ConnectAsync(); return new Sas.DisposeAction(() => { }); })); }
public void joinWithMethod(string method) { if (Client != null) { appendChat("Error: attempted to join again whilst already join(ed/ing)", clr: Color.Purple); return; } appendChat($"Joining game...", clr: Color.Blue); #if DEBUG Client = new WebSocketSharp.WebSocket($"ws://localhost:4650/chess"); #else Client = new WebSocketSharp.WebSocket($"ws://ml-api.uk.ms:4650/chess"); #endif Client.Log.Output = (x, y) => { Console.WriteLine($"{x.Date} {x.Message} {y}"); }; Client.OnMessage += Client_OnMessage; Client.OnClose += Client_OnClose; Client.OnError += Client_OnError; Client.Connect(); var jobj = new JObject(); jobj["token"] = getToken(); jobj["mode"] = method; jobj["cheat"] = Program.Options.UseAntiCheat; Send(new Packet(PacketId.ConnRequest, jobj)); }
/// <inheritdoc/> public void Connect(string uri) { client = new WebSocketSharp.WebSocket(uri); client.OnMessage += (sender, e) => { MessageReceived?.Invoke(e.Data); }; client.OnClose += (sender, e) => { OnDisconnected?.Invoke(); }; client.OnOpen += (sender, e) => { OnConnected?.Invoke(); }; client.OnError += (sender, e) => { OnError?.Invoke(e.Message); }; client.Connect(); }
public void BasicRoundTrip() { var serializer = new JsonCommonSerializer(); var port = new Random().Next(6000, 60000); var listener = new WebSocketServer("ws://localhost:" + port); var serverTransport = listener.GenerateTransportSource("/p1"); var serverRouter = new DefaultMessageRouter(serverTransport, serializer); serverRouter.AddService<IMyService>(new MyService()); listener.Start(); var client = new WebSocket("ws://localhost:" + port + "/p1"); var clientTransport = client.GenerateTransportSource(); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface<IMyService>(); client.Connect(); var result = proxy.Add(3, 4).Result; Assert.Equal(7, result); clientRouter.Dispose(); clientTransport.Dispose(); client.Close(); serverRouter.Dispose(); serverTransport.Dispose(); listener.Stop(); }
private void ExecuteInForeground() { WebSocketSharp.WebSocket ws = new WebSocketSharp.WebSocket(url); Debug.Log("connecting... " + url); ws.OnMessage += (sender, e) => MassageCallBack(e.RawData); while (true) { ws.Connect(); while (!ws.IsConnected) { Thread.Sleep(1000); } while (ws.IsConnected) { byte[] data = PopAgentState(); if (data != null) { ws.Send(data); } //Thread.Sleep(0); } } }
public void WebSocketSharpRoundTrip() { var serializer = new JsonCommonSerializer(); var port = new Random().Next(20000, 60000); var server = WebApp.Start <Startup>("http://localhost:" + port + "/"); var client = new WebSocketSharp.WebSocket("ws://localhost:" + port + "/rt1"); var clientTransport = client.GenerateTransportSource(); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface <IMyService>(); client.Connect(); var result = proxy.Add(3, 4).Result; Assert.Equal(7, result); clientRouter.Dispose(); clientTransport.Dispose(); client.Close(); server.Dispose(); }
public Task Connect(string host, CancellationToken cancelToken) { _webSocket = new WebSocketSharp.WebSocket(host); _webSocket.EmitOnPing = false; _webSocket.EnableRedirection = true; _webSocket.Compression = WebSocketSharp.CompressionMethod.Deflate; _webSocket.OnMessage += (s, e) => { if (e.Type == WebSocketSharp.Opcode.Binary) { if (BinaryMessageReceived != null) { BinaryMessageReceived(this, new SocketBinaryEventArgs(e.RawData)); } } else if (e.Type == WebSocketSharp.Opcode.Text) { if (TextMessageReceived != null) { TextMessageReceived(this, new SocketTextEventArgs(e.Data)); } } }; _webSocket.OnError += (s, e) => { }; return(TaskHelper.CompletedTask); }
public IEnumerator Connect() { m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString()); m_Socket.OnMessage += (sender, e) => { m_Messages.Enqueue(e.RawData); }; m_Socket.OnOpen += (sender, e) => { IsConnected = true; }; m_Socket.OnError += (sender, e) => { error = e.Message; Logs.Error(e.Message); }; m_Socket.OnClose += (sender, args) => IsConnected = false; if (SuportsThreads) { ThreadPool.QueueUserWorkItem(status => { m_Socket.Connect(); }); } else { m_Socket.Connect(); } IsConnecting = true; while (!IsConnected && error == null) { yield return(null); } IsConnecting = false; }
public static string StartWSSession(string url, string cmd) { string reply = null; using (var ws = new WebSocketSharp.WebSocket(url)) { int received = 0; // Set the WebSocket events. ws.OnOpen += (sender, e) => { Response jsonmsg = new Response(); jsonmsg.Identifier = 2000; jsonmsg.Message = cmd; jsonmsg.Name = "PowershellWS"; string output = JsonConvert.SerializeObject(jsonmsg); ws.Send(output); }; ws.OnMessage += (sender, e) => { Response response = JsonConvert.DeserializeObject<Response>(e.Data); if (response.Identifier == 2000) { Console.WriteLine(response.Message); reply = response.Message; received ++; ws.Close(); } }; ws.OnError += (sender, e) => Console.WriteLine(e.Message); ws.OnClose += (sender, e) => Console.WriteLine(e.Reason); // Connect to the server. ws.Connect(); while (received < 1){Thread.Sleep(1);} } return reply; }
public void TestEchoSignalingServer() { // Modeling situtaion, when connected client send some message through the signaling mechanism WebSocketSharp.WebSocket receiver = new WebSocketSharp.WebSocket(url_of_signaling, tokens_to_signaling); receiver.Connect(); receiver.Send(Correct_Message); // Time to receive result by Testing object Thread.Sleep(450); receiver.Close(); string TestResult = Tested_Object.LastReceivedMessage; Tested_Object.Dispose(); //Console.WriteLine(TestResult); //Console.WriteLine(Tested_Object.LastReceivedMessage); //string TestResult2 = TestResult; //TestResult2 += "aaa"; //Console.WriteLine(TestResult2); //output: Hello world!!!aaa, but TestResult: Hello world!!! // and string referece type, where here is problem? String class have value semantic. Assert.AreEqual(Correct_Message, TestResult); Assert.Pass(); }
private void connect() { if (wss != null) { wss.Close(); } wss = new WebSocketSharp.WebSocket("ws://1.85.44.234:9612"); wss.WaitTime = new TimeSpan(0, 0, 8); wss.OnMessage += (s, e1) => { Console.WriteLine(e1.Data); sockobj d = JsonConvert.DeserializeObject <sockobj>(e1.Data); if (d.op == "4D") { update(d); } }; wss.OnOpen += (s, e1) => { String a = "{ctp:\"0\",uid:\"" + user0 + "\",utp:\"1\",op:\"0\"}"; lock (wss_lock) { wss.Send(a); } Console.WriteLine(" websocket open!"); }; wss.OnClose += (s, e1) => { Console.WriteLine("close!"); }; wss.OnError += (s, e1) => { Console.WriteLine("error1"); }; wss.Connect(); }
public bool init() { login(); exit = false; rtu = new Dictionary <string, string>(); utr = new Dictionary <string, string>(); dtLastrtu = DateTime.Now.AddDays(-2); //getrtu(); wss = null; start = new List <x1>(); // 等待到达预订开始时间后执行的等待列表。 end = new List <x1>(); // 任务开始后已经发送开始命令,并接收到命令回复的列表(等待到达预订关闭时间后执行的等待列表。) outdate = new List <x1>(); // 过期任务列表 ok = new List <x1>(); // 完成《开始-结束》计划流程的列表 pending = new List <x1>(); // 到了任务开始时间,已经发送了开始命令,还没有收到回复的列表。 pendinge = new List <x1>(); // 到了任务结束时间,已经发送了停止命令,还没有收到回复的列表。 timer1 = new System.Timers.Timer(); timer1.Interval = getrtutimeout; //设置计时器事件间隔执行时间 timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed); timer1.Enabled = true; connect(); jihua = new Thread(new ThreadStart(this.JihuaThread)); jihua.Start(); doo(); return(true); }
private IEnumerator Connect() { ws = new WebSocketSharp.WebSocket(new Uri(webSocketIP).ToString()); ws.OnClose += (sender, e) => { Debug.Log("client disconnected"); }; ws.OnMessage += (sender, e) => { lock (mInQueue) { mInQueue.Enqueue(e.RawData); } }; ws.OnOpen += (sender, e) => { IsConnected = true; processor.OnConnected(this); }; ws.OnError += (sender, e) => wsError = e.Message; ws.ConnectAsync(); while (!IsConnected && wsError == null) { yield return(0); } }
private void SendHeartBeat(WebSocketSharp.WebSocket ws) { var package = new Package(MsgType.ClientHeart, ""); var data = package.Body; ws.SendAsync(data, null); }
public Task Connect(string host, CancellationToken cancelToken) { _webSocket = new WSSharpNWebSocket(host); _webSocket.EmitOnPing = false; _webSocket.EnableRedirection = true; _webSocket.Compression = WebSocketSharp.CompressionMethod.Deflate; _webSocket.SetProxy(_config.ProxyUrl, _config.ProxyCredentials?.UserName, _config.ProxyCredentials?.Password); _webSocket.OnMessage += (s, e) => { if (e.Type == WebSocketSharp.Opcode.Binary) { RaiseBinaryMessage(e.RawData); } else if (e.Type == WebSocketSharp.Opcode.Text) { RaiseTextMessage(e.Data); } }; _webSocket.OnError += async(s, e) => { _parent.RaiseOnLog(LogMessageSeverity.Error, e.Exception?.GetBaseException()?.Message ?? e.Message); await _parent.DisconnectInternal(e.Exception, skipAwait : true).ConfigureAwait(false); }; _webSocket.OnClose += async(s, e) => { string code = e.WasClean ? e.Code.ToString() : "Unexpected"; string reason = e.Reason != "" ? e.Reason : "No Reason"; Exception ex = new Exception($"Got Close Message ({code}): {reason}"); await _parent.DisconnectInternal(ex, skipAwait : true).ConfigureAwait(false); }; _webSocket.Log.Output = (e, m) => { }; //Dont let websocket-sharp print to console _webSocket.Connect(); return(TaskHelper.CompletedTask); }
public void BasicRoundTrip() { var serializer = new JsonCommonSerializer(); var port = new Random().Next(6000, 60000); var listener = new WebSocketServer("ws://localhost:" + port); var serverTransport = listener.GenerateTransportSource("/p1"); var serverRouter = new DefaultMessageRouter(serverTransport, serializer); serverRouter.AddService <IMyService>(new MyService()); listener.Start(); var client = new WebSocket("ws://localhost:" + port + "/p1"); var clientTransport = client.GenerateTransportSource(); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface <IMyService>(); client.Connect(); var result = proxy.Add(3, 4).Result; Assert.Equal(7, result); clientRouter.Dispose(); clientTransport.Dispose(); client.Close(); serverRouter.Dispose(); serverTransport.Dispose(); listener.Stop(); }
private T SendAndReciveObject <T>(CainiaoPrintDocumentRequest request, string printServerAdd) where T : CainiaoPrintDocumentResponse { WebSocketSharp.WebSocket webSocket = new WebSocketSharp.WebSocket(printServerAdd); try { webSocket.OnMessage += WebSocket_OnMessage; webSocket.OnOpen += WebSocket_OnOpen; webSocket.OnError += WebSocket_OnError; this.data = ""; this.error = ""; this.autoResetEvent.Reset(); //连接 webSocket.Connect(); if (autoResetEvent.WaitOne(5 * 1000) == false) { throw new Exception("等待回收数据超时:5秒"); } if (string.IsNullOrWhiteSpace(this.error) == false || webSocket.ReadyState != WebSocketSharp.WsState.OPEN) { throw new Exception("连接打印组件错误,请检查菜鸟或者拼多多打印组件是否开启:" + this.error); } //发送数据 webSocket.Send(Newtonsoft.Json.JsonConvert.SerializeObject(request)); if (autoResetEvent.WaitOne(60 * 1000) == false) { throw new Exception("等待回收数据超时:60秒"); } if (string.IsNullOrWhiteSpace(this.data)) { throw new Exception("打印组件发送数据失败,没有返回数据:" + this.error); } var response = Newtonsoft.Json.JsonConvert.DeserializeObject <T>(this.data); if (request.requestID != response.requestID) { throw new Exception("发送的请求:" + request.requestID + " 与返回的请求不匹配:" + response.requestID); } if (response.status.Equals("success", StringComparison.OrdinalIgnoreCase) == false) { throw new Exception("发送指令失败:" + response.msg); } return(response); } catch (AggregateException ae) { throw new Exception("连接打印组件错误,请打印是否开启", ae.InnerException); } finally { //关闭连接 if (webSocket != null && webSocket.IsAlive) { webSocket.Close(); } } }
private void MarketData() { decimal openPrice = 0; decimal closePrice = 0; decimal highPrice = 0; decimal lowPrice = 0; DateTime hourTimestamp = DateTime.UtcNow; using (var ws = new WebSocketSharp.WebSocket("wss://www.bitmex.com/realtime")) { ws.OnMessage += (sender, e) => { CryptoLib.Models.Bitmex.Model <CryptoLib.Models.Bitmex.Quote> incomingObject = JsonConvert.DeserializeObject <CryptoLib.Models.Bitmex.Model <CryptoLib.Models.Bitmex.Quote> >(e.Data); PropertyInfo[] incomingProperties = incomingObject.data.FirstOrDefault().GetType().GetProperties(); if (incomingObject.data.FirstOrDefault().timestamp.Date > hourTimestamp.Date || incomingObject.data.FirstOrDefault().timestamp.Hour > hourTimestamp.Hour || incomingObject.data.FirstOrDefault().timestamp.Minute > hourTimestamp.Minute) { CryptoLib.MarketsEntities context = new CryptoLib.MarketsEntities(); CryptoLib.MarketData marketData = new CryptoLib.MarketData { InstrumentID = 1, Timestamp = incomingObject.data.FirstOrDefault().timestamp, OpenPrice = openPrice, ClosePrice = closePrice, HighPrice = highPrice, LowPrice = lowPrice }; if (marketData.OpenPrice != 0 && marketData.ClosePrice != 0 && marketData.HighPrice != 0 && marketData.LowPrice != 0) { context.MarketDatas.Add(marketData); context.SaveChanges(); } openPrice = 0; closePrice = 0; highPrice = 0; lowPrice = 0; hourTimestamp = incomingObject.data.FirstOrDefault().timestamp; } decimal incomingMidPrice = ((incomingObject.data.FirstOrDefault().askPrice + incomingObject.data.FirstOrDefault().bidPrice) / 2); highPrice = Math.Max(incomingMidPrice, highPrice); lowPrice = Math.Min(incomingMidPrice, lowPrice); closePrice = incomingMidPrice; if (openPrice == 0) { openPrice = incomingMidPrice; } if (lowPrice == 0) { lowPrice = incomingMidPrice; } }; ws.Connect(); ws.Send("{\"op\": \"subscribe\", \"args\": \"quote:XBTUSD\"}"); Console.ReadLine(); } }
public static async Task Start(Session session, CancellationToken cancellationToken) { await Task.Delay(30000);//delay running 30s System.Net.ServicePointManager.Expect100Continue = false; cancellationToken.ThrowIfCancellationRequested(); var socketURL = session.LogicSettings.DataSharingDataUrl; using (var ws = new WebSocketSharp.WebSocket(socketURL)) { ws.Log.Level = WebSocketSharp.LogLevel.Error; //ws.OnMessage += (sender, e) => // Console.WriteLine("New message from controller: " + e.Data); while (true) { try { ws.Connect(); Logger.Write("Pokemon spawn point data service connection established."); while (ws.ReadyState == WebSocketSharp.WebSocketState.Open) { lock (events) { while (events.Count > 0) { if (ws.ReadyState == WebSocketSharp.WebSocketState.Open) { var item = events.Dequeue(); var data = Serialize(item); ws.Send($"42[\"pokemon\",{data}]"); } } } await Task.Delay(POLLING_INTERVAL); ws.Ping(); } } catch (IOException) { session.EventDispatcher.Send(new ErrorEvent { Message = "The connection to the data sharing location server was lost." }); } catch (Exception) { } finally { //everytime disconnected with server bot wil reconnect after 15 sec await Task.Delay(POLLING_INTERVAL, cancellationToken); } } } }
public void Connect() { _webSocket = new WebSocketSharp.WebSocket(_address); _webSocket.OnOpen += (o, e) => { if (OnOpen != null) OnOpen(); }; _webSocket.OnMessage += (o, s) => { if (OnMessage != null) OnMessage(s); }; _webSocket.Connect(); }
public override void Setup(string ip, int port) { base.Setup(ip, port); _socket = new WebSocketSharp.WebSocket(NetTool.GetAddress(ip, port) + "/default"); _socket.OnOpen += (a, b) => { base.OnConnected(); }; _socket.OnClose += (a, b) => { base.OnClosed(); }; _socket.OnMessage += (a, b) => { base.OnReceived(b.RawData); }; }
public IEnumerator Connect() { m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString()); m_Socket.OnMessage += (sender, e) => { m_Messages.Enqueue(e.RawData); }; m_Socket.OnOpen += (sender, e) => { m_IsConnected = true; }; m_Socket.OnError += (sender, e) => { m_Error = e.Message; Logs.Error(e.Message); }; m_Socket.OnClose += (sender, args) => m_IsConnected = false; if (SupportsThreads) { //HACK: When restarting in the Unity Editor, send a ping to the destination first to avoid having Connect() hang for 90 seconds. //https://github.com/alvyxaz/barebones-masterserver/pull/142 //Note: On Windows Store Apps, a stream socket is used to mimic ping functionality. It will try to open connection to specified ip address with port 80. Also you need to enable InternetClient capability in Package.appxmanifest. //https://docs.unity3d.com/ScriptReference/Ping.html Ping ping = new Ping(mUrl.Host); //The ping send/receive takes about a second, so we wait for it to complete. while (!ping.isDone) { yield return(null); } //If the ping succeeded, the time will be 0 or higher, otherwise -1. if (ping.time >= 0) { runThread(() => { m_Socket.Connect(); }); } else { m_Error = "Barebones Websocket: Could not contact \"" + mUrl.Host + "\" with Ping."; } } else { m_Socket.Connect(); } IsConnecting = true; while (!m_IsConnected && m_Error == null) { yield return(null); } IsConnecting = false; }
public void Disconnect() { if (this.websocket != null) { Url = ""; websocket.Close(); websocket = null; } }
public void Connect(string host) { m_socket = new WebSocketSharp.WebSocket(host); m_socket.OnOpen += OnConnectedOpened; m_socket.OnMessage += OnMessageReveived; m_socket.OnClose += OnConnectedClose; m_socket.OnError += OnConnectedError; m_socket.ConnectAsync(); }
public override void Setup(string ip, int port) { base.Setup(ip, port); _socket = new WebSocketSharp.WebSocket(NetTool.GetAddress(ip, port) + "/default"); _socket.Log.Level = WebSocketSharp.LogLevel.Error; // _socket.WaitTime = TimeSpan.FromSeconds(1); _socket.OnOpen += (a, b) => { base.OnConnected(); }; _socket.OnClose += (a, b) => { base.OnClosed(); }; _socket.OnMessage += (a, b) => { base.OnReceived(b.RawData); }; }
void InitWebsocketConnection() { Uri wsUri = new Uri("ws://192.168.0.184:4040/main.html", UriKind.Absolute); wsClient = new WebSocketSharp.WebSocket(wsUri.AbsoluteUri); wsClient.Connect(); isWSConnected = true; wsClient.OnOpen += WsClient_OnOpen; wsClient.OnMessage += WsClient_OnMessage; }
public void Dispose() { _disposed = true; websocket?.Close(); websocket = null; http?.Dispose(); http = null; }
public WebSocketSharpConnectionImpl(WebSocketSharp.WebSocket ws) { ws.OnMessage += (s, e) => { OnMessage(this, e.Data); }; ws.OnError += (s, e) => { OnError(this, e.Message); }; WS = ws; }
public Task Connect(string host, CancellationToken cancelToken) { _webSocket = new WSSharpNWebSocket(host); _webSocket.EmitOnPing = false; _webSocket.EnableRedirection = true; _webSocket.Compression = WebSocketSharp.CompressionMethod.None; _webSocket.OnMessage += (s, e) => RaiseProcessMessage(e.Data); _webSocket.OnError += (s, e) => _parent.RaiseOnLog(LogMessageSeverity.Error, $"Websocket Error: {e.Message}"); _webSocket.Connect(); return TaskHelper.CompletedTask; }
public DdpConnection(string url) { coroutineHelper = CoroutineHelper.GetInstance(); coroutineHelper.StartCoroutine(HandleMessages()); ws = new WebSocketSharp.WebSocket(url); ws.OnOpen += OnWebSocketOpen; ws.OnError += OnWebSocketError; ws.OnClose += OnWebSocketClose; ws.OnMessage += OnWebSocketMessage; }
public void Connect() { #if UNITY_WEBGL && !UNITY_EDITOR m_NativeRef = SocketCreate(mUrl.ToString()); #else m_Socket = new WebSocketSharp.WebSocket(mUrl.ToString()); m_Socket.OnMessage += (sender, e) => m_Messages.Enqueue(e.RawData); m_Socket.OnError += (sender, e) => m_Error = e.Message; m_Socket.ConnectAsync(); #endif }
private async Task SendMessage(string soketId, WebSocketSharp.WebSocket soket, string message) { if (!string.IsNullOrEmpty(soketId)) { await SendMessageAsync(soketId, message); return; } soket?.Send(message); }
public Task Disconnect() { string ignored; while (_sendQueue.TryDequeue(out ignored)) { } var socket = _webSocket; _webSocket = null; if (socket != null) socket.Close(); return TaskHelper.CompletedTask; }
/// <summary> /// Initializes a new instance of the <see cref="NativeWebSocket" /> class. /// </summary> /// <param name="socket">The socket.</param> /// <param name="logger">The logger.</param> /// <exception cref="System.ArgumentNullException">socket</exception> public SharpWebSocket(WebSocketSharp.WebSocket socket, ILogger logger) { if (socket == null) { throw new ArgumentNullException("socket"); } if (logger == null) { throw new ArgumentNullException("logger"); } _logger = logger; WebSocket = socket; socket.OnMessage += socket_OnMessage; socket.OnClose += socket_OnClose; socket.OnError += socket_OnError; WebSocket.ConnectAsServer(); }
public Task Connect(string host, CancellationToken cancelToken) { _webSocket = new WSSharpNWebSocket(host); _webSocket.EmitOnPing = false; _webSocket.EnableRedirection = true; _webSocket.Compression = WebSocketSharp.CompressionMethod.None; _webSocket.OnMessage += (s, e) => RaiseProcessMessage(e.Data); _webSocket.OnError += async (s, e) => { _parent.RaiseOnLog(LogMessageSeverity.Error, $"Websocket Error: {e.Message}"); await _parent.DisconnectInternal(e.Exception, skipAwait: true); }; _webSocket.OnClose += async (s, e) => { string code = e.WasClean ? e.Code.ToString() : "Unexpected"; string reason = e.Reason != "" ? e.Reason : "No Reason"; Exception ex = new Exception($"Got Close Message ({code}): {reason}"); await _parent.DisconnectInternal(ex, skipAwait: true); }; _webSocket.Log.Output = (e, m) => { }; //Dont let websocket-sharp print to console _webSocket.Connect(); return TaskHelper.CompletedTask; }
public WebSocketClient(IMessageInterpreter interpreter, string url) { _webSocket = new WebSocketSharp.WebSocket(url); _webSocket.OnMessage += (sender, args) => OnMessage?.Invoke(sender, interpreter.InterpretMessage(args?.Data ?? "")); _webSocket.OnClose += (sender, args) => OnClose?.Invoke(sender, args); }
public void WebSocketSharpRoundTrip() { var serializer = new JsonCommonSerializer(); var port = new Random().Next(20000, 60000); var server = WebApp.Start<Startup>("http://localhost:" + port + "/"); var client = new WebSocketSharp.WebSocket("ws://localhost:" + port + "/rt1"); var clientTransport = client.GenerateTransportSource(); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface<IMyService>(); client.Connect(); var result = proxy.Add(3, 4).Result; Assert.Equal(7, result); clientRouter.Dispose(); clientTransport.Dispose(); client.Close(); server.Dispose(); }
public WebSocketInstance(string url, MyExtensions.Logging.Logger logger) { this.logger = logger; bound = false; instanceLock = new object(); inboundBacklog = new List<string>(); outboundBacklog = new List<string>(); connection = new WebSocketSharp.WebSocket(url); connection.OnMessage += OnMessage; }
public void Benchmark() { var serializerSource = new Newtonsoft.Json.JsonSerializer(); var serializer =new JsonCommonSerializer(serializerSource); // new ProtobufCommonSerializer();// var port = new Random().Next(6000, 60000); var listener = new WebSocketServer("ws://localhost:" + port); var serverTransport = listener.GenerateTransportSource("/p1"); var serverRouter = new DefaultMessageRouter(serverTransport, serializer); serverRouter.AddService<ISumService>(new SumService()); listener.Start(); var client = new WebSocket("ws://localhost:" + port + "/p1"); //client.Compression = WebSocketSharp.CompressionMethod.Deflate; var clientTransport = client.GenerateTransportSource(); var clientRouter = new DefaultMessageRouter(clientTransport, serializer); var proxy = clientRouter.AddInterface<ISumService>(); client.Connect(); const int randCnt = 100; var rand = new Random(42); var randoms = new int[randCnt]; for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000); var package = new SumPackage { Numbers = randoms }; var sw = new Stopwatch(); long timeFromClient = 0, timeToClient = 0; const int cnt = 1000; for (int j = 0; j < cnt; j++) { sw.Start(); //var sum = proxy.Sum(randoms).Result; var sum = proxy.SumPackage(package).Result; sw.Stop(); Assert.Equal(randoms.Sum(), sum); for (int i = 0; i < randCnt; i++) randoms[i] = rand.Next(10000000, 20000000); var times = proxy.TimeDiff(Stopwatch.GetTimestamp()).Result; timeFromClient += times.Item1; timeToClient += Stopwatch.GetTimestamp() - times.Item2; } _testOutputHelper.WriteLine("Completed {0} sum passes in {1}ms", cnt, sw.ElapsedMilliseconds); _testOutputHelper.WriteLine("Client to server latency: {0}us", timeFromClient / cnt / 10); _testOutputHelper.WriteLine("Server to client latency: {0}us", timeToClient / cnt / 10); sw.Reset(); var tree = new SumServiceTree(); SumServiceTree.FillTree(tree, rand, 2); _testOutputHelper.WriteLine("Starting large message transfer."); sw.Start(); var result = proxy.Increment(tree).Result; sw.Stop(); Assert.Equal(tree.Leaf + 1, result.Leaf); _testOutputHelper.WriteLine("Completed large transfer in {0}ms", sw.Elapsed.TotalMilliseconds); clientRouter.Dispose(); clientTransport.Dispose(); client.Close(); serverRouter.Dispose(); serverTransport.Dispose(); listener.Stop(); }
public Task Connect(string host, CancellationToken cancelToken) { _webSocket = new WebSocketSharp.WebSocket(host); _webSocket.EmitOnPing = false; _webSocket.EnableRedirection = true; _webSocket.Compression = WebSocketSharp.CompressionMethod.Deflate; _webSocket.OnMessage += (s, e) => { if (e.Type == WebSocketSharp.Opcode.Binary) { if (BinaryMessageReceived != null) BinaryMessageReceived(this, new SocketBinaryEventArgs(e.RawData)); } else if (e.Type == WebSocketSharp.Opcode.Text) { if (TextMessageReceived != null) TextMessageReceived(this, new SocketTextEventArgs(e.Data)); } }; _webSocket.OnError += (s, e) => { }; return TaskHelper.CompletedTask; }