/// <summary> /// New socket connection /// </summary> /// <param name="client">The socket client</param> /// <param name="socket">The socket</param> public SocketConnection(SocketClient client, IWebsocket socket) { log = client.log; socketClient = client; pendingRequests = new List <PendingRequest>(); handlers = new List <SocketSubscription>(); Socket = socket; Socket.Timeout = client.SocketNoDataTimeout; Socket.OnMessage += ProcessMessage; Socket.OnClose += () => { if (lostTriggered) { return; } DisconnectTime = DateTime.UtcNow; lostTriggered = true; if (ShouldReconnect) { ConnectionLost?.Invoke(); } }; Socket.OnClose += SocketOnClose; Socket.OnOpen += () => { PausedActivity = false; Connected = true; }; }
public MessageProvider(IWebsocket webSocket, ILogger logger) { _webSocket = webSocket; _logger = logger; webSocket.Opened += WebSocket_Opened; webSocket.Received += WebSocket_Received; }
private static IWebsocket CreateSocket() { bool open = false; bool closed = true; IWebsocket obj = Mock.Of <IWebsocket>(); var socket = Mock.Get(obj); socket.Setup(s => s.Close()).Returns(Task.FromResult(true)).Callback(() => { var closing = socket.Object.IsOpen; open = false; closed = true; if (closing) { socket.Raise(s => s.OnClose += null); } OnClose?.Invoke(socket); }); socket.Setup(s => s.IsOpen).Returns(() => open); socket.Setup(s => s.Send(It.IsAny <string>())).Callback(new Action <string>((data) => { OnSend?.Invoke(socket, data); })); socket.Setup(s => s.IsClosed).Returns(() => closed); socket.Setup(s => s.Connect()).Returns(Task.FromResult(true)).Callback(() => { socket.Setup(s => s.IsOpen).Returns(() => open); socket.Setup(s => s.IsClosed).Returns(() => closed); open = true; closed = false; socket.Raise(s => s.OnOpen += null); OnOpen?.Invoke(socket); }); return(socket.Object); }
public NewMainViewModel(IWebsocket websocket) { this.websocket = websocket; this.websocket.Connected += this.Connected; this.websocket.MessageReceived += this.MessageReceived; }
private void WebsocketOnMessage(IWebsocket ws, string data) { if (ws != websocket) { return; } try { var msg = MessageSerialization.Deserialize(data); Log(LogLevel.Trace, "socket", string.Format("received: {0}", msg)); if (channels.ContainsKey(msg.topic)) { channels[msg.topic].Trigger(msg); } OnMessage?.Invoke(data); } catch (Exception e) { UnityEngine.MonoBehaviour.print("CATCHED EXCEPTION!"); UnityEngine.MonoBehaviour.print(e); } }
public async Task Connect() { Protocol = new Protocol(true); socket = new Websocket(Receive); ApiToken = await FFB.Instance.Api.GetToken(); try { string uri = "ws://fumbbl.com:22223/command"; //string uri = "ws://localhost:22227/command"; await Task.Delay(100); LogManager.Info($"Networking Connecting to {uri}"); MainHandler.Instance.AddReport(RawString.Create($"Connecting to {uri}")); await socket.Connect(uri); LogManager.Debug("Networking Connected"); RequestVersion(); } catch (Exception e) { LogManager.Error($"<style=\"Error\">Error connecting: {e.Message}</style>"); MainHandler.Instance.AddReport(RawString.Create($"<style=\"Error\">Error connecting: {e.Message}</style>")); } }
public static BitfinexSocketClient CreateAuthenticatedSocketClient(IWebsocket socket, BitfinexSocketClientOptions options = null) { return(CreateSocketClient(socket, options ?? new BitfinexSocketClientOptions() { ApiCredentials = new ApiCredentials("Test", "Test"), LogVerbosity = LogVerbosity.Debug })); }
private void OnConnMessage(IWebsocket websocket, string rawMessage) { var message = Opts.MessageSerializer.Deserialize(rawMessage); if (message.Ref != null && message.Ref == _pendingHeartbeatRef && Opts.HeartbeatInterval.HasValue) { _heartbeatTimer?.Cancel(); _pendingHeartbeatRef = null; Opts.DelayedExecutor.Execute(SendHeartbeat, Opts.HeartbeatInterval.Value); } if (HasLogger()) { Log(LogLevel.Debug, "receive", $"Received {message}"); } // copy channels before triggering callbacks, since they might modify the channels list _channels.ToList().ForEach(channel => { // violates tell don't ask, but that's how Phoenix JS is implemented if (channel.IsMember(message)) { channel.Trigger(message); } }); OnMessage?.Invoke(message); }
public EngineIO(IWebsocket websocket, string url, string path = "/socket.io", Options options = null) { this.options = options == null ? new Options() : options; this.url = url; this.path = path; _websocket = websocket; _websocket.onmessage += (s, e) => { if (e.Value.IsText) { Receive(e.Value.Data); } }; _websocket.onclose += (s, e) => { emit("close", e.Value.reason); }; _websocket.onerror += (s, e) => { emit("error", e.Value); }; if (this.options.autoConnect) { connect(); } }
public WebsocketMessageProvider(IWebsocket websocket, IDataServer server) { _websocket = websocket; _server = server; websocket.Opened += Websocket_Opened; websocket.Received += Websocket_Received; }
public MessageProvider(IWebsocket websocket, MessageParser parser) { _websocket = websocket; _parser = parser; websocket.Received += Websocket_Received; websocket.Opened += Websocket_Opened; }
/// <summary> /// Handler for a socket closing. Reconnects the socket if needed, or removes it from the active socket list if not /// </summary> /// <param name="socket">The socket that was closed</param> protected virtual void SocketOnClose(IWebsocket socket) { if (socket.ShouldReconnect) { if (socket.Reconnecting) { return; // Already reconnecting } socket.Reconnecting = true; log.Write(LogVerbosity.Info, $"Socket {socket.Id} Connection lost, will try to reconnect"); Task.Run(() => { Thread.Sleep(ReconnectInterval); socket.Reset(); if (!socket.Connect().Result) { log.Write(LogVerbosity.Debug, $"Socket {socket.Id} failed to reconnect"); return; // Connect() should result in a SocketClosed event so we end up here again } var time = socket.DisconnectTime; socket.DisconnectTime = null; if (time == null) { return; } log.Write(LogVerbosity.Info, $"Socket {socket.Id} reconnected after {DateTime.UtcNow - time}"); SocketSubscription subscription; lock (sockets) subscription = sockets.Single(s => s.Socket == socket); socket.Reconnecting = false; if (!SocketReconnect(subscription, DateTime.UtcNow - time.Value)) { socket.Close().Wait(); // Close so we end up reconnecting again } else { log.Write(LogVerbosity.Info, $"Socket {socket.Id} successfully resubscribed"); } }); } else { log.Write(LogVerbosity.Info, $"Socket {socket.Id} closed"); socket.Dispose(); lock (sockets) { var subscription = sockets.SingleOrDefault(s => s.Socket.Id == socket.Id); if (subscription != null) { sockets.Remove(subscription); } } } }
public void Start() { _websocket = new WebSocket(WebsocketUrl); _websocket.Opened += Websocket_Opened; //weak referenceにしたい _websocket.Received += Websocket_Received; //weak referenceにしたい Work = _websocket.ReceiveAsync(); }
private void Create() { socket = SocketFactory.CreateWebsocket(baseAddress); socket.OnClose += SocketClosed; socket.OnError += SocketError; socket.OnOpen += SocketOpened; socket.OnMessage += SocketMessage; }
private void DisposeWebSocket() { _websocket.OnError -= WebSocketOnError; _websocket.OnOpen -= WebSocketOnOpened; _websocket.OnClose -= WebSocketOnClosed; _websocket.OnMessage -= WebSocketOnMessageReceived; _websocket = null; }
private void DisposeWebSocket() { websocket.OnError -= WebSocketOnError; websocket.OnClose -= WebSocketOnClosed; websocket.OnMessage -= WebSocketOnMessageReceived; websocket.Dispose(); websocket = null; }
public static IBinanceSocketClient CreateSocketClient(IWebsocket socket, BinanceSocketClientOptions options = null) { IBinanceSocketClient client; client = options != null ? new BinanceSocketClient(options) : new BinanceSocketClient(); client.SocketFactory = Mock.Of <IWebsocketFactory>(); Mock.Get(client.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny <Log>(), It.IsAny <string>())).Returns(socket); return(client); }
private void OnConnError(IWebsocket websocket, string error) { if (HasLogger()) { Log(LogLevel.Debug, "transport", $"Error {error}"); } OnError?.Invoke(error); TriggerChanError(); }
public static KrakenSocketClient CreateAuthenticatedSocketClient(IWebsocket socket, KrakenSocketClientOptions?options = null) { KrakenSocketClient client; client = options != null ? new KrakenSocketClient(options) : new KrakenSocketClient(new KrakenSocketClientOptions() { LogLevel = LogLevel.Debug, ApiCredentials = new ApiCredentials("Test", "Test") }); client.SocketFactory = Mock.Of <IWebsocketFactory>(); Mock.Get(client.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny <Log>(), It.IsAny <string>())).Returns(socket); return(client); }
public static IHuobiSocketClient CreateSocketClient(IWebsocket socket, HuobiSocketClientOptions options = null) { IHuobiSocketClient client; client = options != null ? new HuobiSocketClient(options) : new HuobiSocketClient(new HuobiSocketClientOptions() { LogVerbosity = LogVerbosity.Debug, ApiCredentials = new ApiCredentials("Test", "Test") }); client.SocketFactory = Mock.Of <IWebsocketFactory>(); Mock.Get(client.SocketFactory).Setup(f => f.CreateWebsocket(It.IsAny <Log>(), It.IsAny <string>())).Returns(socket); return(client); }
/// <summary> /// 初始化委托 /// </summary> /// <param name="invoke"></param> private void InitInvoke(IWebsocket invoke) { websocketSvr.Start(socket => { socket.OnOpen = () => { if (!remoteConnections.TryGetValue(socket.ConnectionInfo.Id, out var conn)) { conn = new RemoteConnection(); conn.socket = socket; remoteConnections.TryAdd(socket.ConnectionInfo.Id, conn); } invoke.OnOpen(conn); }; socket.OnClose = () => { if (remoteConnections.TryRemove(socket.ConnectionInfo.Id, out var conn)) { invoke.OnClose(conn); conn.tag = null; conn.message = null; conn.socket = null; } }; socket.OnMessage = message => { if (remoteConnections.TryGetValue(socket.ConnectionInfo.Id, out var conn)) { conn.message = message; invoke.OnMessage(conn); } }; socket.OnBinary = buffer => { if (remoteConnections.TryGetValue(socket.ConnectionInfo.Id, out var conn)) { conn.buffer = buffer; invoke.OnBinary(conn); } }; socket.OnError = exception => { if (remoteConnections.TryGetValue(socket.ConnectionInfo.Id, out var conn)) { invoke.OnError(conn, exception); } }; }); }
private void WebsocketOnOpen(IWebsocket ws) { if (ws != websocket) { return; } Log(LogLevel.Debug, "socket", "on open"); state = State.Open; RejoinChannels(); SendHeartbeat(); OnOpen?.Invoke(); }
private void WebsocketOnError(IWebsocket ws, string message) { if (ws != websocket || state == State.Closed) { return; } Log(LogLevel.Info, "socket", message ?? "unknown"); state = State.Closed; TriggerChannelError("socket error"); CancelHeartbeat(); OnError?.Invoke(message); websocket = null; }
// PhoenixJS: we use C# delegates instead of callbacks // // public Subscription OnOpen(Action callback) // public Subscription OnClose(Action callback) // public Subscription OnError(Action callback) // public Subscription OnMessage(Action callback) private void OnConnOpen(IWebsocket websocket) { if (HasLogger()) { Log(LogLevel.Debug, "transport", $"Connected to {EndPointUrl()}"); } _closeWasClean = false; // establishedConnections++; FlushSendBuffer(); _reconnectTimer?.Reset(); ResetHeartbeat(); OnOpen?.Invoke(); }
private void WebsocketOnOpen(IWebsocket ws) { if (ws != websocket) { return; } Log(LogLevel.Debug, "socket", "on open"); closeWasClean = false; state = State.Open; RejoinChannels(); CancelReconnect(); ResetHeartbeat(); OnOpen?.Invoke(); }
private void OnConnClose(IWebsocket websocket, ushort code, string reason) { if (HasLogger()) { Log(LogLevel.Debug, "transport", $"Close {code} {reason}"); } TriggerChanError(); _heartbeatTimer?.Cancel(); if (!_closeWasClean && code != 1_000) { _reconnectTimer?.ScheduleTimeout(); } OnClose?.Invoke(code, reason); }
private void WebsocketOnClose(IWebsocket ws, ushort code, string message) { if (ws != websocket || state == State.Closed) { return; } Log(LogLevel.Debug, "socket", string.Format("on close: ({0}) - {1}", code, message ?? "NONE")); state = State.Closed; TriggerChannelError("socket close"); CancelHeartbeat(); OnClose?.Invoke(code, message); websocket = null; }
private void PerformConnect(string url) { if (_websocket != null) { DisposeWebSocket(); } _webSocketTokenSource = new CancellationTokenSource(); _webSocketTokenSource.Token.Register(WebSocketTokenSourceCanceled); CancellationTokenSource.CreateLinkedTokenSource(_webSocketTokenSource.Token, _disconnectToken); // SignalR uses https, websocket4net uses wss url = url.Replace("http://", "ws://").Replace("https://", "wss://"); IDictionary <string, string> cookies = new Dictionary <string, string>(); if (_connection.CookieContainer != null) { var container = _connection.CookieContainer.GetCookies(new Uri(_connection.Url)); foreach (Cookie cookie in container) { cookies.Add(cookie.Name, cookie.Value); } } // Add the header from the connection to the socket connection var headers = _connection.Headers.ToList(); // _websocket = new WebsocketNative(url, _connection.CookieContainer.GetCookieHeader(new Uri(url)), BittrexSocketClient.GetUserAgentString()); #if !NETSTANDARD _websocket = new WebsocketSharp(url, _connection.CookieContainer.GetCookieHeader(new Uri(url)), BittrexSocketClient.GetUserAgentString()); #else _websocket = new Websocket4Net(url, cookies, _connection.Headers); #endif _websocket.OnError += WebSocketOnError; _websocket.OnOpen += WebSocketOnOpened; _websocket.OnClose += WebSocketOnClosed; _websocket.OnMessage += WebSocketOnMessageReceived; _websocket.setProxy(_connection.Proxy); _websocket.Open(); }
protected override void OnStart(IConnection con, string conData, CancellationToken disconToken) { connection = con; connectionData = conData; var connectUrl = UrlBuilder.BuildConnect(connection, Name, connectionData); if (websocket != null) { DisposeWebSocket(); } // SignalR uses https, websocket4net uses wss connectUrl = connectUrl.Replace("http://", "ws://").Replace("https://", "wss://"); IDictionary <string, string> cookies = new Dictionary <string, string>(); if (connection.CookieContainer != null) { var container = connection.CookieContainer.GetCookies(new Uri(connection.Url)); foreach (Cookie cookie in container) { cookies.Add(cookie.Name, cookie.Value); } } websocket = new BaseSocket(log, connectUrl, cookies, connection.Headers); websocket.OnError += WebSocketOnError; websocket.OnClose += WebSocketOnClosed; websocket.OnMessage += WebSocketOnMessageReceived; websocket.DataInterpreterString = interpreter; if (connection.Proxy != null) { var proxy = connection.Proxy.GetProxy(new Uri(connectUrl)); websocket.SetProxy(proxy.Host, proxy.Port); } if (!websocket.Connect().Result) { TransportFailed(new Exception("Can't connect")); } }
private void WebsocketOnMessage(IWebsocket ws, string data) { if (ws != websocket) { return; } var msg = MessageSerialization.Deserialize(data); Log(LogLevel.Trace, "socket", string.Format("received: {0}", msg.ToString())); if (channels.ContainsKey(msg.topic)) { channels[msg.topic].Trigger(msg); } if (OnMessage != null) { OnMessage(data); } }
public JsonLayer(IWebsocket connection) { this.Connection = connection; this.Connection.OnMessage += OnConnectionMessage; }