void OnClientMessage(WebSocketConnection sender, DataReceivedEventArgs e) { User user = Users.Single(a => a.Connection == sender); if (e.Data.Contains("/nick")) { string[] tmpArray = e.Data.Split(new char[] { ' ' }); if (tmpArray.Length > 1) { string myNewName = tmpArray[1]; while (Users.Where(a => a.Name == myNewName).Count() != 0) { myNewName += "_"; } if (user.Name != null) wss.SendToAll("server: '" + user.Name + "' changed name to '" + myNewName + "'"); else sender.Send("you are now know as '" + myNewName + "'"); user.Name = myNewName; } } else { string name = (user.Name == null) ? unknownName : user.Name; wss.SendToAllExceptOne(name + ": " + e.Data, sender); sender.Send("me: " + e.Data); } }
public void Setup() { _socketMock = new Mock<ISocket>(); _handlerMock = new Mock<IHandler>(); _connection = new WebSocketConnection(_socketMock.Object, b => new WebSocketHttpRequest(), r => _handlerMock.Object); }
public void Setup() { _socketMock = new Mock<ISocket>(); _handlerMock = new Mock<IHandler>(); _connection = new WebSocketConnection(_socketMock.Object, connection => { }, b => new WebSocketHttpRequest(), r => _handlerMock.Object, s => default(string)); }
public void Setup() { _socketMock = new Mock<ISocket>(); _handlerFactoryMock = new Mock<IHandlerFactory>(); _connection = new WebSocketConnection(_socketMock.Object, _handlerFactoryMock.Object); _handlerMock = new Mock<IHandler>(); _handlerFactoryMock .Setup(x => x.BuildHandler(It.IsAny<byte[]>(), It.IsAny<Action<string>>(), It.IsAny<Action>())) .Returns(_handlerMock.Object); }
public void ShouldNotRaiseInitializeIfHandlerFactoryReturnsNull() { bool initializeRaised = false; var connection = new WebSocketConnection(_socketMock.Object, conn => { initializeRaised = true; }, b => new WebSocketHttpRequest(), r => null); _socketMock.SetupGet(x => x.Connected).Returns(true); SetupReadLengths(1, 0); connection.StartReceiving(); Assert.IsFalse(initializeRaised); }
void OnClientDisconnected(WebSocketConnection sender, EventArgs e) { try { User user = Users.Single(a => a.Connection == sender); string name = (user.Name == null) ? unknownName : user.Name; wss.SendToAll("server: " + name + " disconnected"); Users.Remove(user); } catch (Exception exc) { Console.WriteLine("ehm..."); } }
/// <summary> /// Initializes a new instance of the Client class with the specified game server and underlying web socket connection. /// </summary> /// <param name="parent">The game server that this client is connected to.</param> /// <param name="connection">The underlying web socket connection that is associated with this client.</param> public Client(CardServer parent, WebSocketConnection connection) { Info = new ClientInfo(); server = parent; thisType = this.GetType(); conn = connection; // Web socket event hookup (not really events). conn.OnMessage = ReceiveMessage; conn.OnOpen = Connected; conn.OnClose = Disconnected; Info.ID = Guid.NewGuid().ToString(); }
public void ShouldRaiseInitializeOnFirstRead() { bool initializeRaised = false; var connection = new WebSocketConnection(_socketMock.Object, conn => { initializeRaised = true; }, b => new WebSocketHttpRequest(), r => _handlerMock.Object, s => default(string)); _socketMock.SetupGet(x => x.Connected).Returns(true); SetupReadLengths(1, 0); connection.StartReceiving(); Assert.IsTrue(initializeRaised); }
public void OnAccept(IAsyncResult ar) { try { Socket clientSocket = m_server_socket.EndAccept(ar); IConnection new_client = new WebSocketConnection(clientSocket); new_client.DataReceived += OnDataReceived; new_client.Disconnected += OnDisconnect; m_connection_list.Add(new_client); var handler = Connected; if (handler != null) { Connected(new_client, new EventArgs()); } m_server_socket.BeginAccept(new AsyncCallback(OnAccept), null); } catch (Exception ex) { //Console.WriteLine(ex.Message, "SGSserverTCP"); } }
public async override Task <string> HandleMessage(WebSocketConnection connection, BinaryReader reader) { if (!connection.avatarRequestRateLimiter.TryTakePoints(1)) { connection.SendMessage(new ErrorMessageSender(ErrorMessageSender.AVATAR_REQUEST_RATE_LIMIT)); return(string.Empty); } await base.HandleMessage(connection, reader); //Get GUID Guid id = ReadMinecraftUUIDFromBinaryReader(reader); try { //Open connection to database using (DatabaseAccessor dba = new DatabaseAccessor()) { //Get avatar data from the database byte[] avatarData = await dba.GetAvatarData(id); //If the array is empty, there is no data for this avatar. if (avatarData == null) { return("NO AVATAR"); } //Reply with avatar data connection.SendMessage(new AvatarProvideResponse(avatarData)); return("SUCCESS"); } } catch (Exception e) { Logger.LogMessage(e.ToString()); } return("N/A"); }
public async Task <IActionResult> Get() { var context = ControllerContext.HttpContext; if (context.WebSockets.IsWebSocketRequest) { var webSocket = await context.WebSockets.AcceptWebSocketAsync(); Console.WriteLine($"Accepted connection '{context.Connection.Id}'"); var connection = new WebSocketConnection(webSocket); await connection.ReceiveUntilClose(); await connection.Close(); return(new EmptyResult()); } else { return(new StatusCodeResult((int)HttpStatusCode.BadRequest)); } }
private async Task ServerSetup(WebSocketConnection connection) { Sockets.Add(connection); connection.onMessage = async(data) => { Log($"[Message]: {data}"); await connection.SendAsync(Resolve(data)); }; connection.onClose = () => { Log($"[Closing connection]: {connection}"); Sockets.Remove(connection); }; connection.onError = () => { Log($"[Error! Closing connection]: {connection}"); Sockets.Remove(connection); }; Log("[Sending message] Connected"); await connection.SendAsync("Connected"); }
private void OnMessageReceived(WebSocketConnection sender, WebSocketRequestMessage request) { WebSocketResponseMessage response = createWebSocketResponse(request); Debug.WriteLine($"Verb: {request.Verb}, Path {request.Path}, Body({request.Body.Length}): {request.Body}, Id: {request.Id}"); try { if (isSignalServiceEnvelope(request)) { SignalServiceEnvelope envelope = new SignalServiceEnvelope(request.Body.ToByteArray(), credentialsProvider.GetSignalingKey()); MessageReceived(this, envelope); } } //catch (Exception e) { } // ignore for now finally { websocket.sendResponse(response); } }
public Task Run() { return(Task.Run(() => { var uri = new Uri("ws://localhost:8080/websocket"); var connection = new WebSocketConnection(uri, new SockJsConverter()); var client = new Client(connection); var random = RandomString(7); client.OnConntected += () => { Console.WriteLine("Connected"); client.Subscribe("description", random, additionalHeader: new Dictionary <string, string>() { ["activemq.subscriptionName"] = "description" }); }; client.OnMessageReceived += message => { Console.WriteLine("Message ->"); Console.WriteLine(message.Body); }; client.OnError += (s, message) => { Console.WriteLine(s); }; client.OnReceipt += message => { Console.WriteLine("Receipt ->"); Console.WriteLine(message.Body); }; client.Connect(random); })); }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); long id = conn.Int64Message.Value; await conn.ReceiveAsync(); string token = conn.TextMessage; await conn.ReceiveAsync(); string name = conn.TextMessage; using (var cmd = npgConn.CreateCommand()) { if (!AuthorizationChecker.ValidateToken(cmd, id, token)) { await conn.SendByteAsync((byte)EResponse.AccountError); return; } try { cmd.CommandText = $"UPDATE account SET name='{name}' WHERE id={id};"; cmd.ExecuteNonQuery(); } catch (NpgsqlException) { await conn.SendByteAsync((byte)EResponse.ServerError); return; } await conn.SendByteAsync((byte)EResponse.Ok); } }
private static void OnReadCompleted(object sender, SocketAsyncEventArgs eventArgs) { Contract.Assert(eventArgs != null, "'eventArgs' MUST NOT be NULL."); WebSocketConnection thisPtr = eventArgs.UserToken as WebSocketConnection; Contract.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL."); #if DEBUG Contract.Assert(Interlocked.Decrement(ref thisPtr.m_OutstandingOperations.m_Reads) >= 0, "'thisPtr.m_OutstandingOperations.m_Reads' MUST NOT be negative."); #endif if (WebSocketBase.LoggingEnabled) { Logging.Enter(Logging.WebSockets, thisPtr, Methods.OnReadCompleted, GetIOCompletionTraceMsg(eventArgs)); } if (eventArgs.SocketError != SocketError.Success) { if (!thisPtr.m_IgnoreReadError) { thisPtr.m_ReadTaskCompletionSource.TrySetException(new SocketException(eventArgs.SocketError)); } else { thisPtr.m_ReadTaskCompletionSource.TrySetResult(0); } } else { thisPtr.m_ReadTaskCompletionSource.TrySetResult(eventArgs.BytesTransferred); } if (WebSocketBase.LoggingEnabled) { Logging.Exit(Logging.WebSockets, thisPtr, Methods.OnReadCompleted, string.Empty); } }
public async Task Invoke(HttpContext context) { if (context.WebSockets.IsWebSocketRequest) { if (ValidateOrigin(context)) { var textSubProtocol = NegotiateSubProtocol(context.WebSockets.WebSocketRequestedProtocols); var webSocketCompressionProvider = _compressionService.NegotiateCompression(context); var webSocket = await context.WebSockets.AcceptWebSocketAsync(textSubProtocol?.SubProtocol); var webSocketConnection = new WebSocketConnection(webSocket, webSocketCompressionProvider, textSubProtocol ?? _options.DefaultSubProtocol, _options.ReceivePayloadBufferSize); webSocketConnection.ReceiveText += async(sender, message) => { await webSocketConnection.SendAsync(message, CancellationToken.None); }; _connectionsService.AddConnection(webSocketConnection); await webSocketConnection.ReceiveMessagesUntilCloseAsync(); if (webSocketConnection.CloseStatus.HasValue) { await webSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None); } _connectionsService.RemoveConnection(webSocketConnection.Id); } else { context.Response.StatusCode = StatusCodes.Status403Forbidden; } } else { context.Response.StatusCode = StatusCodes.Status400BadRequest; } }
public void SwitchToOpaqueMode(WebSocketBase webSocket) { Contract.Assert(webSocket != null, "'webSocket' MUST NOT be NULL."); Contract.Assert(!m_InOpaqueMode, "SwitchToOpaqueMode MUST NOT be called multiple times."); if (m_InOpaqueMode) { throw new InvalidOperationException(); } m_WebSocketConnection = BaseStream as WebSocketConnection; if (m_WebSocketConnection != null && m_IsFastPathAllowed) { if (WebSocketBase.LoggingEnabled) { Logging.Associate(Logging.WebSockets, this, m_WebSocketConnection); } m_WebSocketConnection.SwitchToOpaqueMode(webSocket); m_InOpaqueMode = true; } }
public void Disconnect(bool waitForComplete) { CheckIfCalledOnValidThread(); Logger.Debug(TAG, $"Disconnect WebSocket. State: {State}"); if (State == WebSocketConnectionState.Registered) { // Send "bye" to WebSocket server. SendByeMessage(); State = WebSocketConnectionState.Connected; } if (State == WebSocketConnectionState.Connected || State == WebSocketConnectionState.Error) { if (waitForComplete) { _mre = new ManualResetEvent(false); } WebSocketConnection.Close(); State = WebSocketConnectionState.Closed; if (waitForComplete) { try { _mre.WaitOne(CloseTimeout); } catch (Exception ex) { Logger.Error(TAG, $"Wait error:{ex}"); } } } UnWireEvents(); Logger.Debug(TAG, "Disconnecting WebSocket done."); }
public static void Run() { // start listening connections TcpListener server = new TcpListener(System.Net.IPAddress.Any, Program.ajuste.puertoWeb); server.Start(); // generate options for the future socket connections NetEventIOServer_Options options = new NetEventIOServer_Options(onWebSocketPasswordLogin, onWebSocketTokenLogin, Program.websocketPubSub.onSubscribe, Program.websocketPubSub.onUnsubscribe, Program.websocketPubSub.onUnsubscribeAll); Console.WriteLine("WebSocket server listening."); // wait for more TCP clients while (true) { TcpClient client = server.AcceptTcpClient(); NetworkStream stream = client.GetStream(); Console.WriteLine("WebSocket client connected :D"); new Thread(new ThreadStart(() => { WebSocketConnection conn = new WebSocketConnection(client, stream); if (!conn.connect()) { return; } NetEventIO clientIO = new NetEventIO(conn, options); new Thread(new ThreadStart(clientIO.Run)).Start(); clientIO.onDisconnect = onWebSocketDisconnect; AdminController.addEventListeners(clientIO); })).Start(); } }
async Task IResponse.Response(HttpContext context, WebSocketConnection conn, NpgsqlConnection npgConn) { await conn.ReceiveAsync(); string email = conn.TextMessage; await conn.ReceiveAsync(); string hashedPassword = Account.Hash.Password(conn.TextMessage); await conn.ReceiveAsync(); string name = conn.TextMessage; string hash = Account.Hash.VerificationKey(email); try { using (var cmd = npgConn.CreateCommand()) { cmd.CommandText = $"INSERT INTO account (email, pw, name) VALUES ('{email}', '{hashedPassword}', '{name}');" + $"INSERT INTO verifying_hash VALUES ('{email}', '{hash}');"; cmd.ExecuteNonQuery(); await MailSender.SendVerificationMailAsync(Startup.MailApiKey, email, name, hash); } await conn.SendByteAsync((byte)EResponse.Ok); } catch (NpgsqlException e) { await conn.SendByteAsync((byte)EResponse.ServerError); throw e; } }
public async override Task <string> HandleMessage(WebSocketConnection connection, BinaryReader reader) { if (!connection.avatarUploadRateLimiter.TryTakePoints(1)) { connection.SendMessage(new ErrorMessageSender(ErrorMessageSender.AVATAR_UPLOAD_RATE_LIMIT)); return(string.Empty); } int avatarLength = reader.ReadInt32(); (sbyte retCode, Guid avatarID) = await connection.connectionUser.TryAddAvatar(reader.ReadBytes(avatarLength)); switch (retCode) { //Success case 0: OnSuccess(avatarID, connection); break; //Fail, too many avatars case 1: OnTooManyAvatars(connection); break; //Fail, empty avatar data case 2: OnEmptyAvatar(connection); break; //Fail, not enough space. case 3: OnNotEnoughSpace(connection); break; } return(string.Empty); }
public IGameWebSocketConnection Get(WebSocket ws, IReadOnlyDictionary <string, string> requestHeaders) { if (!requestHeaders.TryGetValue("session-token", out var token)) { logger.LogWarning("No Session Token when trying to create websocket connection!"); return(null); } var sessionToken = sessionManager.Get(token); if (!CheckSessionTokenValidity(sessionToken)) { logger.LogWarning("Invalid session token for websocket connection (" + (sessionToken?.SessionId.ToString() ?? "Token Unavailble") + ")"); return(null); } var session = new WebSocketConnection( logger, ravenBotApi, integrityChecker, inventoryProvider, gameData, gameManager, packetManager, packetSerializer, sessionManager, extWsProvider, this, ws, sessionToken); #if DEBUG logger.LogDebug("[" + sessionToken.TwitchUserName + "] WebSocket Connection Established."); #endif return(socketSessions[sessionToken.SessionId] = session.Start()); }
public static void StartListenNewBlocks(Action <dynamic> block_result) { webSocket = new WebSocketConnection(); webSocket.onOpen = () => { webSocket.SendMessage("{\"id\": 1, \"method\": \"eth_subscribe\", \"params\": [\"newHeads\"], \"jsonrpc\":\"2.0\"}"); }; webSocket.onMessage = (message) => { dynamic response = null; try{ response = JObject.Parse(message); }catch (Exception ex) { Logger.LogStatus(ConsoleColor.Red, "ERROR: " + ex); Environment.Exit(1); return; } if (response != null && response.@params != null && [email protected] != null) { Task.Run(() => { block_result([email protected]); }); } }; webSocket.onError = (error) => { Logger.LogStatus(ConsoleColor.Red, AppConfig.WebsocketNodeUrl + " " + error.Message); Environment.Exit(1); }; webSocket.onClose = () => { Logger.LogStatus(ConsoleColor.Red, "Connection with " + AppConfig.WebsocketNodeUrl + " has been closed"); Environment.Exit(1); }; webSocket.Connect(AppConfig.WebsocketNodeUrl); }
protected void Disposing(bool dispose) { if (dispose & !disposed) { disposed = true; shutdown = true; if (connection != null) { try { if (connection.IsConnected) { connection.CloseAsync().GetAwaiter(); } connection = null; } catch (Exception ex) { logger?.LogError($"Fault disposing web socket in SCADA client adapter - {ex.Message}"); } } if (channel != null) { try { channel.Dispose(); } catch (Exception ex) { logger?.LogError($"Fault disposing channel in SCADA client adapter - {ex.Message}"); } } } }
public async override Task <string> HandleMessage(WebSocketConnection connection, BinaryReader reader) { await base.HandleMessage(connection, reader); Guid id = ReadMinecraftUUIDFromBinaryReader(reader); byte[] getHash; using (DatabaseAccessor accessor = new DatabaseAccessor()) { string s = await accessor.GetAvatarHashForUser(id); if (s == null) { return(string.Empty); } getHash = Encoding.UTF8.GetBytes(s); } connection.SendMessage(new UserAvatarHashProvideResponse(id, getHash)); return(string.Empty); }
public async Task Invoke(HttpContext context) { if (!context.WebSockets.IsWebSocketRequest) { await _next.Invoke(context); // can we have a request to the same path and not for a WS connection? Consider using the code on the next line //context.Response.StatusCode = StatusCodes.Status400BadRequest; return; } var webSocket = await context.WebSockets.AcceptWebSocketAsync().ConfigureAwait(false); var webSocketConnection = new WebSocketConnection(webSocket); _connectionsService.AddConnection(webSocketConnection); await webSocketConnection.ReceiveMessagesUntilCloseAsync(); //await Receive(webSocket, /*async*/ (result, serializedMessage) => //{ // if (result.MessageType == WebSocketMessageType.Text) // { // //Message message = JsonConvert.DeserializeObject<Message>(serializedMessage, _jsonSerializerSettings); // //await _webSocketHandler.ReceiveAsync(socket, result, message).ConfigureAwait(false); // return; // } //}); if (webSocketConnection.CloseStatus.HasValue) { // the close handshake shouldn't be completed on prematurely closed connections await webSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None); } _connectionsService.RemoveConnection(webSocketConnection.Id); }
private void handleIncomingMessage(string mess, WebSocketConnection connection) { char[] sc = {Convert.ToChar(4), Convert.ToChar(3)}; string[] vals = mess.Split(sc); List<string> messParams = new List<string>(); for (int i = 0; i < vals.Length; i++) { if (i % 2 == 0) { messParams.Add(vals[i]); } } messParams.RemoveAt(messParams.Count - 1); string[] returnStrings = mh(messParams.ToArray()); string separator = Convert.ToChar(4).ToString(); string returnString = ""; foreach (string s in returnStrings) { returnString += s; returnString += separator; } connection.socket.Send(formatedMessage(messParams[0] + separator + messParams[1] + separator + returnString)); }
static void Main(string[] args) { Console.WriteLine("Press any key to connect..."); Console.ReadKey(); using var ws = new WebSocket("wss://localhost:34198/command"); var connection = new WebSocketConnection(ws, "username", "password"); connection.OnMessageReceived += (sender, e) => OnMessageReceived(sender, e); Console.WriteLine("Client is running..."); Console.WriteLine("Type a command. Type quit to exit"); var nextLine = Console.ReadLine(); while (nextLine.ToLowerInvariant() != "quit") { var commands = nextLine.Split(' '); var commandHasPayload = Commands.CommandHasPayload(commands[0]); Commands.ExecuteRemotely(connection, new Request(commands[0], commands.SubArray(1, commands.Length - 1))); nextLine = Console.ReadLine(); } }
// According to my tests even when aborting the underlying Socket the completionEvent for // SocketAsyncEventArgs is not always fired, which can result in not cancelling the underlying // IO. Cancelling the TaskCompletionSources below is safe, because CompletionSource.Tryxxx // is handling the race condition (whoever is completing the CompletionSource first wins.) internal static void OnCancel(object state) { Contract.Assert(state != null, "'state' MUST NOT be NULL."); WebSocketConnection thisPtr = state as WebSocketConnection; Contract.Assert(thisPtr != null, "'thisPtr' MUST NOT be NULL."); if (WebSocketBase.LoggingEnabled) { Logging.Enter(Logging.WebSockets, thisPtr, Methods.OnCancel, string.Empty); } try { TaskCompletionSource <int> readTaskCompletionSourceSnapshot = thisPtr.m_ReadTaskCompletionSource; if (readTaskCompletionSourceSnapshot != null) { readTaskCompletionSourceSnapshot.TrySetCanceled(); } TaskCompletionSource <object> writeTaskCompletionSourceSnapshot = thisPtr.m_WriteTaskCompletionSource; if (writeTaskCompletionSourceSnapshot != null) { writeTaskCompletionSourceSnapshot.TrySetCanceled(); } } finally { if (WebSocketBase.LoggingEnabled) { Logging.Exit(Logging.WebSockets, thisPtr, Methods.OnCancel, string.Empty); } } }
public async Task Invoke(HttpContext context) { if (context.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync(); WebSocketConnection webSocketConnection = new WebSocketConnection(webSocket); _connectionsService.AddConnection(webSocketConnection); await webSocketConnection.WaitUntilCloseAsync(); if (webSocketConnection.CloseStatus.HasValue) { await webSocket.CloseAsync(webSocketConnection.CloseStatus.Value, webSocketConnection.CloseStatusDescription, CancellationToken.None); } _connectionsService.RemoveConnection(webSocketConnection.Id); } else { context.Response.StatusCode = StatusCodes.Status400BadRequest; } }
private static async Task ExecuteChannel(bool listen) { try { const string uri = "ws://127.0.0.1:5001"; WriteStatus($"connecting to {uri}..."); var socket = await WebSocketConnection.ConnectAsync(uri); WriteStatus("connected"); int clientNumber = Interlocked.Increment(ref Program.clientNumber); var named = new ClientWebSocketWithIdentity(socket, clientNumber); lock (clients) { clients.Add(named); } ClientChannelReceiveMessages(named); } catch (Exception ex) { WriteStatus(ex.GetType().Name); WriteStatus(ex.Message); } }
private void Listen() { int nextConnectionId = 0; while (true) { try { Socket socket = m_RootListenerSocket.Accept(); WebSocketConnection connection = new WebSocketConnection(); connection.socket = socket; connection.thread = new Thread(ProcessConnection); connection.thread.IsBackground = true; connection.id = nextConnectionId; nextConnectionId++; connection.thread.Start(connection); lock (m_Connections) m_Connections.Add(connection); } catch (SocketException ex) { Console.WriteLine("\nIn startListening\n" + ex.Message); } } }
private void Disconnected(WebSocketConnection connection) { this.socketSessions.Remove(connection.SessionId, out _); }
void OnClientConnected(object sender, ClientConnectedEventArgs e) { connection = e.Client; }
public WebSocketServerChannel(WebSocketConnection socket) { socketConnection = socket; }
private void DisconnectedHandler(WebSocketConnection sender, EventArgs e) { handshakeComplete = false; }
private void OnClientConnect(IAsyncResult ar) { var clientSocket = ListenerSocket.EndAccept(ar); // ListenerSocket.BeginAccept(null, 0, OnAccept, null); ShakeHands(clientSocket); LogLine(DateTime.Now + "> new connection from " + clientSocket.LocalEndPoint, ServerLogLevel.Subtle); var clientConnection = new WebSocketConnection(clientSocket); Connections.Add(clientConnection); clientConnection.Disconnected += new WebSocketDisconnectedEventHandler(ClientDisconnected); if (ClientConnected != null) { ClientConnected(clientConnection, EventArgs.Empty); } if (LogLevel != ServerLogLevel.Nothing) { clientConnection.DataReceived += new DataReceivedEventHandler(DataReceivedFromClient); } ListenForClients(); }
public void SendToAllExceptOne(string data, WebSocketConnection indifferent) { foreach (var client in Connections) { if (client != indifferent) { client.Send(data); } } }
/// <summary> /// Establishes the connection /// </summary> public void Connect() { string host = uri.Host; StringBuilder path = new StringBuilder(uri.AbsolutePath); if (path.Length == 0) { path.Append('/'); } string query = uri.Query; if (!string.IsNullOrEmpty(query)) { path.Append("?"); path.Append(query); } string origin = "http://" + host; socket = CreateSocket(); IPEndPoint localEndPoint = (IPEndPoint)socket.LocalEndPoint; int port = localEndPoint.Port; if (port != 80) { host = host + ":" + port; } networkStream = new NetworkStream(socket); outputStream = new StreamWriter(networkStream, Encoding.UTF8); StringBuilder extraHeaders = new StringBuilder(); foreach (var headerEntry in headers) { extraHeaders.AppendFormat("{0}: {1}\r\n", headerEntry.Key, headerEntry.Value); } string request = string.Format( "GET {0} HTTP/1.1\r\n" + "Upgrade: WebSocket\r\n" + "Connection: Upgrade\r\n" + "Host: {1}\r\n" + "Origin: {2}\r\n" + "{3}" + "\r\n", path, host, origin, extraHeaders); byte[] encodedHandshake = Encoding.UTF8.GetBytes(request); networkStream.Write(encodedHandshake, 0, encodedHandshake.Length); networkStream.Flush(); inputStream = new StreamReader(networkStream); string header = inputStream.ReadLine(); if (!header.Equals("HTTP/1.1 101 Web Socket Protocol Handshake")) { throw new InvalidOperationException("Invalid handshake response"); } header = inputStream.ReadLine(); if (!header.Equals("Upgrade: WebSocket")) { throw new InvalidOperationException("Invalid handshake response"); } header = inputStream.ReadLine(); if (!header.Equals("Connection: Upgrade")) { throw new InvalidOperationException("Invalid handshake response"); } // Ignore any further response do { header = inputStream.ReadLine(); } while (!header.Equals("")); handshakeComplete = true; connection = new WebSocketConnection(socket); connection.DataReceived += new DataReceivedEventHandler(DataReceivedHandler); connection.Disconnected += new WebSocketDisconnectedEventHandler(DisconnectedHandler); connection.Error += new EventHandler(ErrorHandler); }
void ConnectionOpen(WebSocketConnection socket) { Debug.Log("Connection Opened!"); }
public override void OnClosed(WebSocketConnection socket) { Console.WriteLine("Socket closed: " + socket.ID); }
public override void OnMessage(WebSocketConnection socket, string message) { Console.WriteLine("Message from client: " + message); }
void OnClientConnected(WebSocketConnection sender, EventArgs e) { Users.Add(new User() { Connection = sender }); sender.Disconnected += new WebSocketDisconnectedEventHandler(OnClientDisconnected); sender.DataReceived += new DataReceivedEventHandler(OnClientMessage); }
private void DataReceivedHandler(WebSocketConnection sender, DataReceivedEventArgs e) { FireOnMessage(e); }
void ClientDisconnected(WebSocketConnection sender, EventArgs e) { Connections.Remove(sender); LogLine(DateTime.Now + "> " + sender.ConnectionSocket.LocalEndPoint + "disconnected", ServerLogLevel.Subtle); }
public WebSocketStream(WebSocketConnection connection) { _connection = connection; }
/// <summary> /// Accepts a new WebSocketConnection object and creates a new game <see cref="Client" /> based on it. /// </summary> /// <param name="conn">The connection to use for the new client.</param> public void NewClient(WebSocketConnection conn) { Clients.Add(new Client(this, conn)); }
public void AddConnection(WebSocketConnection connection) { _connections.TryAdd(connection.Id, connection); }
public WebSocketGameServer() { IgnoreExtensions = true; connection = new WebSocketConnection(); connection.server = this; }
void DataReceivedFromClient(WebSocketConnection sender, DataReceivedEventArgs e) { Log(DateTime.Now + "> data from " + sender.ConnectionSocket.LocalEndPoint + "disconnected", ServerLogLevel.Subtle); Log(": " + e.Data + "\n" + e.Size + " bytes", ServerLogLevel.Verbose); LogLine("", ServerLogLevel.Subtle); }
protected override void Connect(System.Threading.CancellationToken token) { WebSocketConnection connection = new WebSocketConnection(this); connection.Start(token); }