public ChatHandler(RichTextBox messageList, RichTextBox roomMessageList) { this.messageList = messageList; this.roomMessageList = roomMessageList; websocket = new WebSocket("ws://" + ClientBase.serverAdress + PORT_ROUTE); websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(receiveChat); websocket.Open(); }
public MainWindow() { InitializeComponent(); if (serverURL == "") { textBox1.Text = "[エラー]"; textBox2.Text = "[エラー]\n"; textBox2.Text += " サーバのURLを講義担当者から聞いてserverURL変数にセットしてください\n"; } else { websocket = new WebSocket(serverURL); websocket.Closed += new EventHandler(websocket_Closed); websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error); websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived); websocket.Opened += new EventHandler(websocket_Opened); textBox2.Text += "[使い方]\n"; textBox2.Text += " 上のテキストボックスに入力しenterか送信ボタンでサーバへ送信されます。\n"; textBox2.Text += " サーバは得たデータの先頭に'Server said'と付けて、そのまま返します。\n"; textBox2.Text += " サーバから帰って来た文字列がこのテキストボックスに表示されます。\n"; textBox2.Text += " 発言の先頭に「all:」を付けて送信すると、サーバに接続している全員に送られます。\n"; textBox2.Text += "[init]\n"; textBox1.Focus(); websocket.Open(); } }
public void FetchConnections() { if (!_isConnected) throw new Exception("Not connected"); _socket = new WebSocket("wss://www.irccloud.com/", "", _cookies, null, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)", "https://www.irccloud.com"); _socket.MessageReceived += socket_MessageReceived; _socket.Open(); }
public Task Connect(string host, CancellationToken cancelToken) { try { _webSocket = new WebSocketClient(host); _webSocket.EnableAutoSendPing = false; _webSocket.NoDelay = true; _webSocket.Proxy = null; _webSocket.DataReceived += OnWebSocketBinary; _webSocket.MessageReceived += OnWebSocketText; _webSocket.Error += OnWebSocketError; _webSocket.Closed += OnWebSocketClosed; _webSocket.Opened += OnWebSocketOpened; _waitUntilConnect.Reset(); _waitUntilDisconnect.Reset(); _webSocket.Open(); _waitUntilConnect.Wait(cancelToken); _taskManager.ThrowException(); //In case our connection failed } catch { _waitUntilDisconnect.Set(); throw; } return(TaskHelper.CompletedTask); }
public void ReConnect(string symbol, dynamic form, string timeFrame) { IsSocketOpened = false; list = new List <MapSymbolChart>(); webSocket = new WebSocket4Net.WebSocket(host); webSocket.Open(); webSocket.Opened += WebSocket_Opened; webSocket.Closed += WebSocket_Closed; webSocket.Error += WebSocket_Error; webSocket.MessageReceived += WebSocket_MessageReceived; while (!IsSocketOpened) { } foreach (var item in listForms) { form.candleData = new BindingList <CandleData>(); if (item.form == form) { SendSymbol(symbol, timeFrame); item.timeFrame = timeFrame; item.symbol = symbol; } else { SendSymbol(item.symbol, item.timeFrame); } } }
/// <summary> /// Initializes a new instance of the <see cref="FchatService" /> class. /// Chat connection is used to communicate with F-Chat using websockets. /// </summary> /// <param name="user"> /// The user. /// </param> /// <param name="eventagg"> /// The eventagg. /// </param> /// <param name="socket"></param> /// <param name="provider"></param> public FchatService(IAccount user, IEventAggregator eventagg, WebSocket socket, ITicketProvider provider) { this.socket = socket; this.provider = provider; Account = user.ThrowIfNull("user"); events = eventagg.ThrowIfNull("eventagg"); events.GetEvent<CharacterSelectedLoginEvent>() .Subscribe(ConnectToChat, ThreadOption.BackgroundThread, true); errsThatDisconnect = new[] { Constants.Errors.NoLoginSlots, Constants.Errors.NoServerSlots, Constants.Errors.KickedFromServer, Constants.Errors.SimultaneousLoginKick, Constants.Errors.BannedFromServer, Constants.Errors.BadLoginInfo, Constants.Errors.TooManyConnections, Constants.Errors.UnknownLoginMethod }; InitializeLog(); autoPingTimer.Elapsed += (s, e) => TrySend(Constants.ClientCommands.SystemPing); autoPingTimer.Start(); staggerTimer = new Timer(GetNextConnectDelay()); // first reconnect is 5 seconds staggerTimer.Elapsed += (s, e) => DoReconnect(); }
public RpcClient(string ip, int port) { var uri = string.Format("ws://{0}:{1}/", ip, port); _client = new WebSocket(uri); _client.NoDelay = true; _client.Opened += (sender, args) => Task.Run(() => DispatchConnected()); _client.Closed += (sender, args) => Task.Run(() => SafeCall(DispatchDisconnected)); Send = message => SafeCall(() => { var data = RpcMessage.Write(message); _client.Send(data); }); _client.MessageReceived += (sender, args) => SafeCall(() => { var data = args.Message; var message = RpcMessage.Read(data); Task.Run(() => ProcessMessage(message)); }); Task.Run(() => SafeCall(_client.Open)); }
public void Start() { if (_ws != null) return; string wsUrl; if (!string.IsNullOrEmpty(_symbol)) { wsUrl = string.Format("wss://www.stockfighter.io/ob/api/ws/{0}/venues/{1}/tickertape/stocks/{2}", _account, _venue, _symbol); } else { wsUrl = string.Format("wss://www.stockfighter.io/ob/api/ws/{0}/venues/{1}/tickertape", _account, _venue); } _ws = new WebSocket(wsUrl); _ws.MessageReceived += MessageReceived; _ws.Opened += (s, e) => { if (Started != null) Started(this, EventArgs.Empty); }; _ws.Error += (s, e) => { if (ErrorOccured != null) ErrorOccured(this, e.Exception.Message); }; _ws.Closed += (s, e) => { if (Stopped != null) Stopped(this, EventArgs.Empty); if (_reconnect) _ws.Open(); }; _ws.Open(); }
public WebSocketWrapper(string uri) { m_webSocket = new WebSocket(uri, string.Empty, WebSocketVersion.Rfc6455); m_webSocket.EnableAutoSendPing = false; m_webSocket.MessageReceived += OnMessageReceived; m_webSocket.Error += OnError; }
public MainWindow() { InitializeComponent(); if (serverURL == "") { textBox1.Text = "URL不明!"; } else { textBox1.Text = channel; websocket = new WebSocket(serverURL); websocket.Closed += new EventHandler(websocket_Closed); websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error); websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived); websocket.Opened += new EventHandler(websocket_Opened); websocket.Open(); InitializeComponent(); // aaa //Kinectの初期化 kinect = KinectSensor.KinectSensors[0]; //イベントハンドラの登録 kinect.SkeletonFrameReady += new EventHandler<SkeletonFrameReadyEventArgs>(handler_SkeletonFrameReady); //骨格トラッキングの有効化 kinect.SkeletonStream.Enable(); kinect.Start(); // aaa } }
public void PingPong() { using (NetMQContext context = NetMQContext.Create()) { using (WebSocket4Net.WebSocket webSocket = new WebSocket("ws://localhost:82", "WSNetMQ")) { webSocket.EnableAutoSendPing = true; webSocket.AutoSendPingInterval = 1; // one second using (WSRouter router = context.CreateWSRouter()) { router.Bind("ws://localhost:82"); ManualResetEvent manualResetEvent = new ManualResetEvent(false); webSocket.Opened += (sender, args) => manualResetEvent.Set(); webSocket.Open(); webSocket.Error += (sender, args) => Console.WriteLine("Error"); manualResetEvent.WaitOne(); Thread.Sleep(5000); Assert.AreEqual(webSocket.State, WebSocketState.Open); } } } }
//Object syncLock = new Object(); public OnlineUserHandler(ListView onlineUserList) { this.onlineUserList = onlineUserList; websocket = new WebSocket("ws://" + ClientBase.serverAdress + PORT_ROUTE); websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(handleOnlineUsers); websocket.Open(); }
public void Connect(string url) { Uri uri = null; string connectionId = Strings.RandomString(8); int serverId = Strings.RandomNumber(1, 1000); try { uri = new Uri(url); } catch (Exception) { throw new OrtcEmptyFieldException(String.Format("Invalid URL: {0}", url)); } string prefix = uri != null && "https".Equals(uri.Scheme) ? "wss" : "ws"; Uri connectionUrl = new Uri(String.Format("{0}://{1}:{2}/broadcast/{3}/{4}/websocket", prefix, uri.DnsSafeHost, uri.Port, serverId, connectionId)); // // NOTE: For wss connections, must have a valid installed certificate // See: http://www.runcode.us/q/c-iphone-push-server // _websocket = new WebSocket(connectionUrl.AbsoluteUri); _websocket.Opened += new EventHandler(websocket_Opened); _websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error); _websocket.Closed += new EventHandler(websocket_Closed); _websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived); _websocket.Open(); }
public Task ConnectAsync(string url) { var taskCompletionSource = new TaskCompletionSource <bool>(); try { _socket = new WebSocket4Net.WebSocket(url); _socket.MessageReceived += WebsocketMessageReceived; _socket.Opened += (sender, args) => { Connected?.Invoke(this, EventArgs.Empty); taskCompletionSource.TrySetResult(true); }; _socket.Closed += SocketClosed; _socket.Open(); } catch (Exception ex) { _socket = null; taskCompletionSource.TrySetException(ex); } return(taskCompletionSource.Task); }
static void Main(string[] args) { m_WebSockets = new WebSocket[1000]; var autoEventReset = new AutoResetEvent(false); for(var i = 0; i < m_WebSockets.Length; i++) { var websocket = new WebSocket("ws://localhost:2011/"); websocket.Opened += (s, e) => { autoEventReset.Set(); }; websocket.Error += (s, e) => { Console.WriteLine(e.Exception.Message); autoEventReset.Set(); }; websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived); websocket.Open(); autoEventReset.WaitOne(); m_WebSockets[i] = websocket; Console.WriteLine(i); } Console.WriteLine("All connected"); Console.ReadLine(); }
public Task ConnectAsync(CancellationToken cancellationToken) { var channelOptions = (MqttClientWebSocketOptions)_clientOptions.ChannelOptions; var uri = "ws://" + channelOptions.Uri; var sslProtocols = SslProtocols.None; if (channelOptions.TlsOptions.UseTls) { uri = "wss://" + channelOptions.Uri; #if NETCOREAPP3_0 || NET5_0 sslProtocols = SslProtocols.Tls13; #else sslProtocols = SslProtocols.Tls12; #endif } var subProtocol = channelOptions.SubProtocols.FirstOrDefault() ?? string.Empty; _webSocket = new WebSocket4Net.WebSocket(uri, subProtocol, sslProtocols: sslProtocols); _webSocket.DataReceived += OnDataReceived; _webSocket.Open(); SpinWait.SpinUntil(() => _webSocket.State == WebSocketState.Open, _clientOptions.CommunicationTimeout); return(Task.FromResult(0)); }
public void connection() { _socket = new WebSocket4Net.WebSocket("ws://10.0.3.2:9898"); _socket.Opened += OnConnectionOpen; _socket.MessageReceived += OnMessage; _socket.Open(); }
protected override void DoOpen() { var log = LogManager.GetLogger(Global.CallerName()); log.Info("DoOpen uri =" + this.Uri()); ws = new WebSocket4Net.WebSocket(this.Uri(), "", Cookies, MyExtraHeaders); ws.EnableAutoSendPing = false; if (ServerCertificate.Ignore) { var security = ws.Security; if (security != null) { security.AllowUnstrustedCertificate = true; security.AllowNameMismatchCertificate = true; } } ws.Opened += ws_Opened; ws.Closed += ws_Closed; ws.MessageReceived += ws_MessageReceived; ws.DataReceived += ws_DataReceived; ws.Error += ws_Error; ws.Open(); }
private async Task ConnectInternalAsync(string host) { await DisconnectInternalAsync().ConfigureAwait(false); _disconnectCancelTokenSource?.Dispose(); _cancelTokenSource?.Dispose(); _client?.Dispose(); _disconnectCancelTokenSource = new CancellationTokenSource(); _cancelTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_parentToken, _disconnectCancelTokenSource.Token); _cancelToken = _cancelTokenSource.Token; _client = new WS4NetSocket(host, "", customHeaderItems: _headers.ToList()) { EnableAutoSendPing = false, NoDelay = true, Proxy = null }; _client.MessageReceived += OnTextMessage; _client.DataReceived += OnBinaryMessage; _client.Opened += OnConnected; _client.Closed += OnClosed; _client.Open(); _waitUntilConnect.Wait(_cancelToken); }
public void Connect(string uri) { this.socket = new WebSocket4Net.WebSocket(uri); this.socket.MessageReceived += this.SocketMessageReceived; this.socket.Closed += this.SocketClosed; this.socket.Open(); }
internal RippleApi(IConfiguration config, ILogger logger, IFeeProvider feeProvider, ITransactionSigner txSigner, string dataApiUrl, string exchIssuerAddress, string fiatCurrencyCode) { _config = config; _logger = logger; _feeProvider = feeProvider; _txSigner = txSigner; _dataApiUrl = dataApiUrl; _issuerAddress = exchIssuerAddress; _fiatCurreny = fiatCurrencyCode; _walletAddress = _config.AccessKey; _webSocket = new WebSocket(_rippleSocketUri = _config.GetValue("server")); string proxyHost = _config.GetValue("proxyHost"); string proxyPort = _config.GetValue("proxyPort"); if (null != proxyHost && null != proxyPort) { //TODO: these two lines don't belong here, rather to WebClient2 _webProxy = new WebProxy(proxyHost, int.Parse(proxyPort)); _webProxy.Credentials = CredentialCache.DefaultCredentials; var wsProxy = new HttpConnectProxy(new DnsEndPoint(proxyHost, Int32.Parse(proxyPort)), "1.0"); _webSocket.Proxy = wsProxy; } _webSocket.Opened += websocket_Opened; _webSocket.Error += websocket_Error; _webSocket.Closed += websocket_Closed; _webSocket.MessageReceived += websocket_MessageReceived; }
private void Stop() { if (_ws == null) return; _ws.Close(); _ws = null; }
private Task DisconnectInternalAsync(int closeCode = 1000, bool isDisposing = false) { _disconnectCancelTokenSource.Cancel(); if (_client == null) { return(Task.Delay(0)); } if (_client.State == WebSocketState.Open) { try { _client.Close(closeCode, ""); } catch { } } _client.MessageReceived -= OnTextMessage; _client.DataReceived -= OnBinaryMessage; _client.Opened -= OnConnected; _client.Closed -= OnClosed; try { _client.Dispose(); } catch { } _client = null; _waitUntilConnect.Reset(); return(Task.Delay(0)); }
public static WebSocketDisposable ReserveConnection(string uri) { Tuple<WebSocket, RefCountDisposable> connection; lock(openConnectionsLock) { if(!openConnections.TryGetValue(uri, out connection)) { Debug.WriteLine("Creating new websocket"); WebSocket ws = new WebSocket(uri); // Set callbacks? ws.Open(); var dispose = Disposable.Create(() => { Debug.WriteLine("Disposing of websocket"); ws.Close(); openConnections.Remove(uri); }); RefCountDisposable refCount = new RefCountDisposable(dispose); connection = Tuple.Create(ws, refCount); openConnections.Add(uri, connection); return new WebSocketDisposable(connection.Item1, connection.Item2.GetDisposable()); } } Debug.WriteLine("Returning old websocket"); return new WebSocketDisposable(connection.Item1, connection.Item2.GetDisposable()); }
public async void Start(int port, string uri) { var localIP = ProductConfiguration.LocalIP; var server = new WebSocketServer($"wss://{localIP}:{port}"); client = new WebSocket4Net.WebSocket(uri, version: WebSocketVersion.Rfc6455); server.Certificate = new X509Certificate2(Resources.RedoCert, "CyberAgent"); server.Start(socket => { this.server = socket; socket.OnOpen = () => { server.ListenerSocket.Close(); client.AllowUnstrustedCertificate = true; client.DataReceived += (sender, e) => RecvHandle?.Invoke(new ByteArray(e.Data)); client.Closed += (sender, e) => socket.Close(); client.Open(); }; socket.OnBinary = data => SendHandle?.Invoke(new ByteArray(data)); socket.OnClose = client.Close; }); await Task.Delay(60 * 1000); server.ListenerSocket.Close(); }
public void Connect(string url) { if (_url == string.Empty) _url = "ws://" + url + "/websocket"; if (_socket == null) { Console.WriteLine("Creating WebSocket..."); _socket = new WebSocket(_url); _socket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(socket_MessageReceived); _socket.Opened += new EventHandler(_socket_Opened); _socket.Closed += new EventHandler(_socket_Closed); _socket.Error += _socket_Error; } Console.WriteLine("Connecting..."); //_socket.AutoSendPingInterval = 30; //_socket.EnableAutoSendPing = true; if (!isConnected && _socket.State != WebSocketState.Open) { _socket.Open(); _isWait = 1; this.Wait(); } Console.WriteLine("Connected."); this._client.OnConnected(); }
public void Connect(string url) { session_.Settings.ConnectionURI = url; if (!url.Contains("ws://")) url = "ws://" + url; if (socket_ != null) { if (session_ != null) session_.IsConnected = false; socket_.Close(); socket_ = null; } if (socket_ == null) { session_.Log.Add(new LogMessage { MsgType = MessageType.Info, Message = "Attempting to connect" }); string res = new Uri(url).AbsoluteUri; socket_ = new WebSocket(res); socket_.EnableAutoSendPing = true; socket_.AutoSendPingInterval = 50; socket_.Opened += _Opened; socket_.Closed += _Closed; socket_.MessageReceived += _ReceiveMsg; socket_.DataReceived += _ReceiveData; socket_.Error += _Error; socket_.Open(); } }
public Task Disconnect() { string ignored; while (_sendQueue.TryDequeue(out ignored)) { } var socket = _webSocket; _webSocket = null; if (socket != null) { socket.Close(); socket.Opened -= OnWebSocketOpened; socket.DataReceived -= OnWebSocketBinary; socket.MessageReceived -= OnWebSocketText; _waitUntilDisconnect.Wait(); //We need the next two events to raise this one socket.Error -= OnWebSocketError; socket.Closed -= OnWebSocketClosed; socket.Dispose(); } return(TaskHelper.CompletedTask); }
void Connect(int times=3) { if (times > 0) { try { _socketInstance = new WebSocket(_serverAddress); _socketInstance.Opened += _socketInstance_Opened; _socketInstance.Closed += _socketInstance_Closed; _socketInstance.DataReceived += _socketInstance_DataReceived; _socketInstance.Error += _socketInstance_Error; _socketInstance.Open(); } catch (System.Exception e) { _dispatcher.LogException(e); _dispatcher.LogWarning("Connect Failed! Try again 3 seconds later!"); Connect(times - 1); } } else { _dispatcher.Quit(); } }
public void Connect() { String url; if (String.IsNullOrEmpty(Port) || String.IsNullOrEmpty(Domain)) return; url = String.Format("ws://{0}:{1}{2}", Domain, Port, Path); try { socket = new WebSocket( url, "", Cookies, null, null, "http://" + Domain, WebSocketVersion.DraftHybi10 ); socket.Opened += new EventHandler(socket_Opened); socket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(socket_MessageReceived); socket.Closed += new EventHandler(socket_Closed); socket.Open(); } catch (Exception e) { Debug.Print(String.Format("Websocket connection failed. {0} {1}", url, e.Message)); } }
/// <summary> /// The pump for received messages. /// </summary> /// <param name="socket">The socket.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The observable stream of messages.</returns> private static IObservable <string> SocketReceivePump(WebSocket4Net.WebSocket socket, CancellationToken cancellationToken) { var dispose = new Action[] { null }; var incoming = new BufferBlock <string>(); EventHandler <MessageReceivedEventArgs> received = (sender, args) => incoming.Post(args.Message); socket.MessageReceived += received; EventHandler <ErrorEventArgs> errored = (sender, args) => { ((ITargetBlock <string>)incoming).Fault(args.Exception); dispose[0](); }; socket.Error += errored; EventHandler closed = (sender, args) => dispose[0](); socket.Closed += closed; dispose[0] = () => { incoming.Complete(); socket.MessageReceived -= received; socket.Error -= errored; socket.Closed -= closed; socket.Close(); }; cancellationToken.Register(dispose[0]); return(incoming.AsObservable().Publish().RefCount()); }
public void Start(List <ProductType> productTypes, List <ChannelType> channelTypes = null) { if (WebSocketFeed != null && WebSocketFeed.State != WebSocketState.Closed) { throw new GDAXSharpHttpException( $"Websocket needs to be in the closed state, current state is {WebSocketFeed.State}"); } if (productTypes.Count == 0) { throw new ArgumentException("You must specify at least one product type"); } StopWebSocket = false; ProductTypes = productTypes; ChannelTypes = channelTypes; var socketUrl = SandBox ? SandBoxApiUri : ApiUri; WebSocketFeed = new WebSocket4Net.WebSocket(socketUrl); WebSocketFeed.Closed += WebSocket_Closed; WebSocketFeed.Error += WebSocket_Error; WebSocketFeed.MessageReceived += WebSocket_MessageReceived; WebSocketFeed.Opened += WebSocket_Opened; WebSocketFeed.Open(); }
/// <summary> /// Creates a new <see cref="RoRamu.WebSocket.Client.WebSocket4Net.WebSocket4NetConnection" /> object. /// </summary> /// <param name="connectionInfo">Information about how to connect to the websocket server.</param> public WebSocket4NetConnection(WebSocketConnectionInfo connectionInfo) { if (connectionInfo == null) { throw new ArgumentNullException(nameof(connectionInfo)); } if (!Uri.TryCreate(connectionInfo.RemoteEndpoint, UriKind.Absolute, out Uri endpoint)) { throw new ArgumentException("The provided websocket endpoint is not a well-formed URI string", nameof(connectionInfo)); } if (!WebSocketSchemes.Contains(endpoint.Scheme)) { throw new ArgumentException($"The endpoint scheme must be one of the following: {FormattedWebSocketSchemesList}", nameof(connectionInfo)); } this._socket = new WebSocket4NetImpl.WebSocket( uri: connectionInfo.RemoteEndpoint, customHeaderItems: new List <KeyValuePair <string, string> >(connectionInfo.Headers), cookies: new List <KeyValuePair <string, string> >(connectionInfo.Cookies)); this._socket.MessageReceived += async(sender, messageArgs) => await this.OnMessage?.Invoke(messageArgs.Message); this._socket.DataReceived += async(sender, dataArgs) => await this.OnMessage?.Invoke(dataArgs.Data.DecodeToString()); this._socket.Error += async(sender, errorArgs) => await this.OnError?.Invoke(errorArgs.Exception); this._socket.Closed += async(sender, args) => await this.OnClose?.Invoke(); this._socket.Opened += async(sender, args) => await this.OnOpen?.Invoke(); }
public Task Connect(string host, CancellationToken cancelToken) { try { _webSocket = new WebSocketClient(host); _webSocket.EnableAutoSendPing = false; _webSocket.NoDelay = true; _webSocket.Proxy = null; _webSocket.DataReceived += OnWebSocketBinary; _webSocket.MessageReceived += OnWebSocketText; _webSocket.Error += OnWebSocketError; _webSocket.Closed += OnWebSocketClosed; _webSocket.Opened += OnWebSocketOpened; _waitUntilConnect.Reset(); _waitUntilDisconnect.Reset(); _webSocket.Open(); _waitUntilConnect.Wait(cancelToken); _taskManager.ThrowException(); //In case our connection failed } catch { _waitUntilDisconnect.Set(); throw; } return TaskHelper.CompletedTask; }
public List<SniperInfo> FindAll() { List<SniperInfo> newSniperInfos = new List<SniperInfo>(); try { using (var client = new WebSocket(URL, "basic", WebSocketVersion.Rfc6455)) { client.MessageReceived += (s, e) => { try { var message = e.Message; var match = Regex.Match(message, @"(1?\d+)+\[""helo"",(2?.*)\]"); if (match.Success) { if (match.Groups[1].Value == "42") { var sniperInfos = GetJsonList(match.Groups[2].Value); if (sniperInfos != null && sniperInfos.Any()) { newSniperInfos.AddRange(sniperInfos); } } } else { match = Regex.Match(message, @"(1?\d+)+\[""poke"",(2?.*)\]"); if (match.Success) { if (match.Groups[1].Value == "42") { var sniperInfo = GetJson(match.Groups[2].Value); if (sniperInfo != null) { newSniperInfos.Add(sniperInfo); } } } } } catch (Exception ex) { Log.Debug("Error receiving message from PokemonGoIVClub", ex); } }; client.Open(); Thread.Sleep(Timeout); client.Close(); } } catch (Exception e) { Log.Warn("Received error from Pokezz. More info the logs"); Log.Debug("Received error from Pokezz: ", e); } return newSniperInfos; }
public MainWindow() { InitializeComponent(); if (serverURL == "") { textBox1.Text = "URL不明!"; } else { textBox1.Text = channel; websocket = new WebSocket(serverURL); websocket.Closed += new EventHandler(websocket_Closed); websocket.Error += new EventHandler<SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error); websocket.MessageReceived += new EventHandler<MessageReceivedEventArgs>(websocket_MessageReceived); websocket.Opened += new EventHandler(websocket_Opened); websocket.Open(); drumset = new Drumset(); drumset.SetElements( new CircleTarget("RideCymbal", new Position3D(0.4, 0.3, 2.0), 0.3), new CircleTarget("HiHat", new Position3D(-0.7, 0.1, 2.4), 0.3), new CircleTarget("Drum1", new Position3D(-0.2, 0.0, 2.2), 0.3), new CircleTarget("Drum2", new Position3D(0.5, 0.1, 2.6), 0.3) ); System.Console.WriteLine("Loaded"); foreach (var potentialSensor in KinectSensor.KinectSensors) { if (potentialSensor.Status == KinectStatus.Connected) { this.sensor = potentialSensor; break; } } if (null != this.sensor) { // Turn on the skeleton stream to receive skeleton frames this.sensor.SkeletonStream.Enable(); // Add an event handler to be called whenever there is new color frame data this.sensor.SkeletonFrameReady += this.SensorSkeletonFrameReady; // Start the sensor! try { this.sensor.Start(); } catch (IOException) { this.sensor = null; } } this.sensor.SkeletonStream.TrackingMode = SkeletonTrackingMode.Seated; } }
/// <summary> /// Connects the async. /// </summary> /// <param name="url">The URL.</param> public void Connect(string url) { _socket = new WebSocket4Net.WebSocket(url); _socket.MessageReceived += websocket_MessageReceived; _socket.Open(); }
public WebSocketFeed(bool sandBox) { var socketUrl = sandBox ? ApiUris.WebsocketUriSandbox : ApiUris.WebsocketUri; webSocketFeed = new WebSocket4Net.WebSocket(socketUrl); }
private void CreateWebSocket(string uri) { m_WebSocket = new WebSocket(uri); m_WebSocket.Opened += OnOpened; m_WebSocket.MessageReceived += OnMessageReceieved; m_WebSocket.Error += OnError; m_WebSocket.Closed += OnClosed; }
public void CreateWebSocket(String url) { ws = new WebSocket(url); ws.Opened += (sender, args) => Console.WriteLine("Opened..." + sender.ToString() + "," + args.ToString()); ws.Closed += (sender, args) => Console.WriteLine("Closed..." + sender.ToString() + "," + args.ToString()); ws.MessageReceived += WsOnMessageReceived; ws.Open(); }
public WebSocketFeed(bool sandBox) { var socketUrl = sandBox ? ApiUris.WebsocketUriSandbox : ApiUris.WebsocketUri; webSocketFeed = new WebSocket4Net.WebSocket(socketUrl, sslProtocols: SslProtocols.Tls11 | SslProtocols.Tls12); }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { if (_socket != null) { _socket.Close(); _socket = null; } }
/// <summary> /// Connects. /// </summary> /// <param name="url">The URL.</param> public void Connect(string url) { _socket = new WebSocket4Net.WebSocket(url); _socket.MessageReceived += websocket_MessageReceived; _socket.Open(); }
public MenuBigImgViewForm(WebSocket Connection) { this.Connection = Connection; this.BigImg = null; this.BigImgMemoryStream = null; InitializeComponent(); }
public Aria2cWebSocketWatcher(Aria2cConfig config, Logger logger) { _config = config; _logger = logger; _socket = new WebSocket(_config.WebSocketUrl); AttachEvents(); }
public void Init() { websocket = new WebSocket("ws://localhost:2012/"); websocket.Opened += new EventHandler(websocket_Opened); websocket.Error += new EventHandler <ErrorEventArgs>(websocket_Error); websocket.Closed += new EventHandler(websocket_Closed); websocket.MessageReceived += new EventHandler <MessageReceivedEventArgs>(websocket_MessageReceived); websocket.Open(); }
public Connector(string uri) { _Host = uri; // Socket = new JsonWebSocket(Host); // Socket.On<JsonObject>("Answer", (e) => { handle(e,this); }); Socket = new WebSocket(Host); Socket.Open(); }
private void Form1_Load(object sender, EventArgs e) { websocket = new WebSocket("ws://127.0.0.1:8081"); websocket.Opened += new EventHandler(websocket_Opened); websocket.Error += new EventHandler <SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error); websocket.Closed += new EventHandler(websocket_Closed); websocket.MessageReceived += new EventHandler <MessageReceivedEventArgs>(websocket_MessageReceived); websocket.Open(); }
// private constructor. private BitfinexSocket() { webSocket = new WebSocket4Net.WebSocket(host); webSocket.Open(); webSocket.Opened += WebSocket_Opened; webSocket.Closed += WebSocket_Closed; webSocket.Error += WebSocket_Error; webSocket.MessageReceived += WebSocket_MessageReceived; }
public void Execute() { _socket = new WebSocket4Net.WebSocket(Url); _socket.Opened += OnConnected; _socket.Error += OnError; _socket.Closed += OnClosed; _socket.MessageReceived += OnMessage; _socket.Open(); }
private DataServerClient() { websocket = new WebSocket4Net.WebSocket(ConfigurationManager.AppSettings["WebSocketUri"].ToString()); websocket.Opened += new EventHandler(websocket_Opened); websocket.Error += new EventHandler <ErrorEventArgs>(websocket_Error); websocket.Closed += new EventHandler(websocket_Closed); websocket.MessageReceived += Websocket_MessageReceived; websocket.Open(); }
private void connect_Click(object sender, EventArgs e) { websocket = new WebSocket("ws://114.80.136.56:20718/dataproxy"); websocket.Opened += new EventHandler(websocket_Opened); websocket.Error += new EventHandler<ErrorEventArgs>(websocket_Error); websocket.Closed += new EventHandler(websocket_Closed); websocket.DataReceived += new EventHandler<DataReceivedEventArgs>(websocket_MessageReceived); websocket.Open(); }
public WebSocketRtdServer() { _subMgr = new SubscriptionManager(); _socket = new WebSocket4Net.WebSocket("wss://ws-feed.gdax.com"); // Hack: May not be needed _socket.Security.AllowNameMismatchCertificate = true; _socket.Security.AllowUnstrustedCertificate = true; }
public WSocketClient(string url) { ServerPath = url; this._webSocket = new WebSocket4Net.WebSocket(url); this._webSocket.Opened += WebSocket_Opened; this._webSocket.Error += WebSocket_Error; this._webSocket.Closed += WebSocket_Closed; this._webSocket.MessageReceived += WebSocket_MessageReceived; }
protected override void DoOpen() { var log = LogManager.GetLogger(Global.CallerName()); log.Info("DoOpen uri =" + this.Uri()); ws = new WebSocket4Net.WebSocket(this.Uri(), String.Empty, Cookies, MyExtraHeaders) { EnableAutoSendPing = false }; if (ServerCertificate.Ignore) { var security = ws.Security; if (security != null) { security.AllowUnstrustedCertificate = true; security.AllowNameMismatchCertificate = true; } } ws.Opened += ws_Opened; ws.Closed += ws_Closed; ws.MessageReceived += ws_MessageReceived; ws.DataReceived += ws_DataReceived; ws.Error += ws_Error; var destUrl = new UriBuilder(this.Uri()); if (this.Secure) { destUrl.Scheme = "https"; } else { destUrl.Scheme = "http"; } // We don't want to overwrite a user defined proxy. var hasNoUserDefinedProxy = Proxy == null; if (hasNoUserDefinedProxy) { Proxy = WebRequest.DefaultWebProxy; } // The "Proxy" property could be null, in this case we'll let "IsBypassed" be true, so no proxy is used. var useProxy = !(Proxy?.IsBypassed(destUrl.Uri) ?? true); if (useProxy) { var proxyUrl = Proxy.GetProxy(destUrl.Uri); var proxy = new HttpConnectProxy(new DnsEndPoint(proxyUrl.Host, proxyUrl.Port), destUrl.Host); ws.Proxy = proxy; } ws.Open(); }
/// <summary> /// Return a connected <see cref="WebSocket"/>. /// </summary> /// <param name="uri"> /// The uri to connect the result to. /// </param> /// <returns> /// A connected <see cref="WebSocket"/>. /// </returns> private static async Task <WebSocket4Net.WebSocket> ConnectSocket(Uri uri) { var socket = new WebSocket4Net.WebSocket(uri.ToString()); var opened = Observable.FromEventPattern(_ => socket.Opened += _, _ => socket.Opened -= _); socket.Open(); await opened.ToTask(); return(socket); }
private void websocket_Closed(object sender, EventArgs e) { Console.WriteLine("Websocket CLOSED"); WebSocket4Net.WebSocket ws = (WebSocket4Net.WebSocket)sender; if (ws.State == WebSocketState.Closed) { Console.WriteLine("Websocket CLOSED - probably because the server is OFFLINE"); } }
static void websocket_Error(object sender, SuperSocket.ClientEngine.ErrorEventArgs e) { websocket = null; websocket = new WebSocket("ws://www.palmmud.com:8080"); websocket.Opened += new EventHandler(websocket_Opened); websocket.Error += new EventHandler <SuperSocket.ClientEngine.ErrorEventArgs>(websocket_Error); websocket.Closed += new EventHandler(websocket_Closed); websocket.MessageReceived += new EventHandler <MessageReceivedEventArgs>(websocket_MessageReceived); websocket.Open(); }
/// <summary> /// 连接 url,向服务器端发消息 /// </summary> /// <param name="wsOrWssUrl">ws或wss地址</param> /// <param name="data">要发送的字符串</param> public void SendMsg2(string wsOrWssUrl, string data) { this.data = data; websocket = new WebSocket4Net.WebSocket(wsOrWssUrl); websocket.Opened += websocket_Opened; websocket.Closed += websocket_Closed; websocket.Error += Websocket_Error; websocket.MessageReceived += websocket_MessageReceived; websocket.Open(); }
private string SendCommand(string sessionWSEndpoint, string cmd) { WebSocket4Net.WebSocket j = new WebSocket4Net.WebSocket(sessionWSEndpoint); ManualResetEvent waitEvent = new ManualResetEvent(false); ManualResetEvent closedEvent = new ManualResetEvent(false); string message = ""; byte[] data; Exception exc = null; j.Opened += delegate(System.Object o, EventArgs e) { j.Send(cmd); }; j.MessageReceived += delegate(System.Object o, MessageReceivedEventArgs e) { message = e.Message; waitEvent.Set(); }; j.Error += delegate(System.Object o, SuperSocket.ClientEngine.ErrorEventArgs e) { exc = e.Exception; waitEvent.Set(); }; j.Closed += delegate(System.Object o, EventArgs e) { closedEvent.Set(); }; j.DataReceived += delegate(System.Object o, DataReceivedEventArgs e) { data = e.Data; waitEvent.Set(); }; j.Open(); waitEvent.WaitOne(); if (j.State == WebSocket4Net.WebSocketState.Open) { j.Close(); closedEvent.WaitOne(); } if (exc != null) { throw exc; } return(message); }