public static async Task<WebSocketMessage> ReadMessageAsync(WebSocket webSocket, byte[] buffer, int maxMessageSize) { ArraySegment<byte> arraySegment = new ArraySegment<byte>(buffer); WebSocketReceiveResult receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); // special-case close messages since they might not have the EOF flag set if (receiveResult.MessageType == WebSocketMessageType.Close) { return new WebSocketMessage(null, WebSocketMessageType.Close); } if (receiveResult.EndOfMessage) { // we anticipate that single-fragment messages will be common, so we optimize for them switch (receiveResult.MessageType) { case WebSocketMessageType.Binary: return new WebSocketMessage(BufferSliceToByteArray(buffer, receiveResult.Count), WebSocketMessageType.Binary); case WebSocketMessageType.Text: return new WebSocketMessage(BufferSliceToString(buffer, receiveResult.Count), WebSocketMessageType.Text); default: throw new Exception("This code path should never be hit."); } } else { // for multi-fragment messages, we need to coalesce ByteBuffer bytebuffer = new ByteBuffer(maxMessageSize); bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count)); WebSocketMessageType originalMessageType = receiveResult.MessageType; while (true) { // loop until an error occurs or we see EOF receiveResult = await webSocket.ReceiveAsync(arraySegment, CancellationToken.None).ConfigureAwait(continueOnCapturedContext: false); if (receiveResult.MessageType != originalMessageType) { throw new InvalidOperationException("Incorrect message type"); } bytebuffer.Append(BufferSliceToByteArray(buffer, receiveResult.Count)); if (receiveResult.EndOfMessage) { switch (receiveResult.MessageType) { case WebSocketMessageType.Binary: return new WebSocketMessage(bytebuffer.GetByteArray(), WebSocketMessageType.Binary); case WebSocketMessageType.Text: return new WebSocketMessage(bytebuffer.GetString(), WebSocketMessageType.Text); default: throw new Exception("This code path should never be hit."); } } } } }
private void keyboardHandler(WebSocket ws) { byte[] buffer = new byte[4096 * 4096]; var task = ws.ReceiveAsync(new ArraySegment<byte>(buffer), System.Threading.CancellationToken.None).ContinueWith((ReceiveResult) => { string s = System.Text.Encoding.ASCII.GetString(buffer); s = s.TrimEnd('\0', ' '); foreach (string keyboardCmd in s.Split(' ', '\0')) { string cmd = keyboardCmd.ToLower().Trim(); if (keyboardCmd.StartsWith("up/") && keyboardCmd.Length > "up/".Length) { Keyboard.KeyUp(int.Parse(keyboardCmd.Substring("up/".Length), System.Globalization.NumberStyles.AllowHexSpecifier)); } if (keyboardCmd.StartsWith("down/") && keyboardCmd.Length > "down/".Length) { Keyboard.KeyDown(int.Parse(keyboardCmd.Substring("down/".Length), System.Globalization.NumberStyles.AllowHexSpecifier)); } if (keyboardCmd.StartsWith("tap/") && keyboardCmd.Length > "tap/".Length) { Keyboard.KeyTap(int.Parse(keyboardCmd.Substring("tap/".Length), System.Globalization.NumberStyles.AllowHexSpecifier)); } } keyboardHandler(ws); }); }
public async Task EchoAsync(WebSocket webSocket) { var buffer = new ArraySegment<byte>(new byte[8192]); for (; ;) { var result = await webSocket.ReceiveAsync( buffer, CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { return; } else if (result.MessageType == WebSocketMessageType.Text) { Console.WriteLine("{0}", System.Text.Encoding.UTF8.GetString(buffer.Array, 0, result.Count)); } await webSocket.SendAsync( new ArraySegment<byte>(buffer.Array, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); } }
internal async Task<IAsyncTransport> ConnectAsync(Address address, Action<ClientWebSocketOptions> options) { Uri uri = new UriBuilder() { Scheme = address.Scheme, Port = GetDefaultPort(address.Scheme, address.Port), Host = address.Host, Path = address.Path }.Uri; ClientWebSocket cws = new ClientWebSocket(); cws.Options.AddSubProtocol(WebSocketSubProtocol); if (options != null) { options(cws.Options); } await cws.ConnectAsync(uri, CancellationToken.None); if (cws.SubProtocol != WebSocketSubProtocol) { cws.Abort(); throw new NotSupportedException( string.Format( CultureInfo.InvariantCulture, "WebSocket SubProtocol used by the host is not the same that was requested: {0}", cws.SubProtocol ?? "<null>")); } this.webSocket = cws; return this; }
public async Task ProcessWebSocket(HttpContext context, WebSocket webSocket) { var connection = new Connection(context, webSocket); Console.WriteLine("Connect: {0}", context.Connection.RemoteIpAddress); var cancelToken = CancellationToken.None; var buffer = new byte[1024]; WebSocketReceiveResult received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken); while (!webSocket.CloseStatus.HasValue) { string text = System.Text.Encoding.UTF8.GetString(buffer, 0, received.Count); Console.WriteLine("Recd: {0}", text); try { Cmd.Parse(text, connection)?.Run(); } catch (Exception ex) { Console.WriteLine("Unhandled exception: {0}", ex); } received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), cancelToken); } await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, cancelToken); }
public SocketServer() { var websocket = new WebSocket(); _tcpListener = new TcpListener(IPAddress.Parse("127.0.0.1"), 56837);//8095 _dictionary = new ConcurrentDictionary<string, SocketWrapper>(); _connections = new List<SocketWrapper>(); }
private void TestChatHanlder_OnReceive(WebSocket Socket, WebSocketMessageType Type, byte[] ReceiveMessage) { //並行廣播給所有使用者,也可以轉發給指定使用者 Parallel.ForEach(WebSocketList, async socket => { await socket.SendAsync(new ArraySegment<byte>(ReceiveMessage), Type, true, CancellationToken.None); }); }
private async Task HandleSocket(WebSocket socket) { var receiveBuffer = new byte[1024 * 4]; try { var result = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None); while (!socket.CloseStatus.HasValue) { await Task.WhenAll(tasks: SocketsSingleton.Instance.SocketsBag.Where(x => x.State == WebSocketState.Open) .Select(async x => { await x.SendAsync(new ArraySegment<byte>(receiveBuffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); })); SocketsSingleton.Instance.SocketsBag = new ConcurrentBag<WebSocket>(SocketsSingleton.Instance.SocketsBag.Where(x => x.State == WebSocketState.Open)); result = await socket.ReceiveAsync(new ArraySegment<byte>(receiveBuffer), CancellationToken.None); } await socket.CloseAsync(result.CloseStatus ?? WebSocketCloseStatus.EndpointUnavailable, result.CloseStatusDescription, CancellationToken.None); } catch (Exception exception) { Console.Write(exception); } finally { socket?.Dispose(); } }
public WebsocketSendAsync(WebSocket webSocket, CompletionQueue completion_queue) { if (null == webSocket) throw new ArgumentException(); this.webSocket = webSocket; if (null == completion_queue) throw new ArgumentException(); this.completion_queue = completion_queue; }
public DashboardSocketHandler(WebSocket socket) { Socket = socket; MasterController.Instance.Listener.Status.Updated += ListenerStatusUpdated; MasterController.Instance.Transmitter.Status.Updated += TransmitterStatusUpdated; Venue.Status.Updated += Status_Updated; }
static async Task<Message> ReceiveAsync(WebSocket ws) { byte[] buffer = new byte[4096]; var seg = new ArraySegment<byte>(buffer); var result = await ws.ReceiveAsync(seg, CancellationToken.None); return Message.Deserialize(new ArraySegment<byte>(buffer, 0, result.Count)); }
public SACNTransmitterLive(WebSocket socket) { Socket = socket; var Transmitter = MasterController.Instance.Transmitter as SACNTransmitter; UniverseID = 1; Transmitter.OnTransmit += Transmitter_OnTransmit; }
private static async Task SendMessage(WebSocket webSocket, string msg, bool endOfMessage) { logger.LogVerbose("SendMessage = {0}", msg); var msgBytes = Encoding.UTF8.GetBytes(msg); await webSocket.SendAsync(new ArraySegment<byte>(msgBytes, 0, msgBytes.Length), WebSocketMessageType.Text, endOfMessage, CancellationToken.None); }
public Connection(HttpContext context, WebSocket socket) { Id = Guid.NewGuid(); Context = context; Socket = socket; AccessLevel = AccessLevel.Guest; }
public override async Task ProcessRequestAsync(HttpContext httpContext) { await Task.Run(() => { if (httpContext.IsWebSocketRequest) { httpContext.AcceptWebSocketRequest(async delegate(AspNetWebSocketContext context) { this.Socket = context.WebSocket; while (this.Socket != null || this.Socket.State != WebSocketState.Closed) { ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); WebSocketReceiveResult receiveResult = await this.Socket.ReceiveAsync(buffer, CancellationToken.None); try { switch (receiveResult.MessageType) { case WebSocketMessageType.Text: string message = Encoding.UTF8.GetString(buffer.Array, 0, receiveResult.Count); this.OnMessageReceived(message); break; case WebSocketMessageType.Binary: this.OnMessageReceived(buffer.Array); break; case WebSocketMessageType.Close: this.OnClosing(true, receiveResult.CloseStatusDescription); break; } switch (this.Socket.State) { case WebSocketState.Connecting: this.OnConnecting(); break; case WebSocketState.Open: this.OnOpen(); break; case WebSocketState.CloseSent: this.OnClosing(false, string.Empty); break; case WebSocketState.CloseReceived: this.OnClosing(true, string.Empty); break; case WebSocketState.Closed: this.OnClosed(); break; } } catch (Exception ex) { this.OnError(ex); } } }); } }); }
private async Task Send(WebSocket webSocket, SocketMessage message) { if (webSocket != null && webSocket.State == WebSocketState.Open) { var value = new ArraySegment<byte>(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(message))); await webSocket.SendAsync(value, WebSocketMessageType.Text, true, CancellationToken.None); } }
private WebSocketHost(WebSocket webSocket) { _webSocket = webSocket; _buffer = new byte[1024]; // Start listening for incoming messages _webSocket.ReceiveAsync(new ArraySegment<byte>(_buffer), CancellationToken.None).ContinueWith(ReceiveMessage); }
public MasterMessageDispatcher( IOptions<ServerSettings> settings, IClientMessageFactory clientMessageFactory, WebSocket webSocket, Guid masterClientId, ClientType clientType) :base(settings, clientMessageFactory, webSocket, masterClientId, clientType) { }
public RawDMXSocketHandler(WebSocket socket) { Socket = socket; if (AllSocketHandlers == null) { AllSocketHandlers = new List<RawDMXSocketHandler>(); } Universe = MasterController.Instance.Venue?.Universes.First(); }
public PreviewSocketHandler(WebSocket socket) { Socket = socket; DMX = new byte[Universe.DMX_UNIVERSE_SIZE ]; foreach(Universe universe in MasterController.Instance.Venue?.Universes ?? Enumerable.Empty<Universe>()) { universe.Rendered += Universe_Updated; } }
public Session(SessionFactory factory, WebSocket ws) { this.Factory = factory; this.Id = Guid.NewGuid(); this.Socket = ws; this.Source = new CancellationTokenSource(); this.Buffer = new byte[BufferSize]; receiver = new ArraySegment<byte>(this.Buffer); this.Result = null; }
private async Task Echo(WebSocket webSocket) { byte[] buffer = new byte[1024 * 4]; var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!result.CloseStatus.HasValue) { await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, result.Count), result.MessageType, result.EndOfMessage, CancellationToken.None); result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(result.CloseStatus.Value, result.CloseStatusDescription, CancellationToken.None); }
internal async Task Add(string id, WebSocket connection) { Connections.Add(new ConnectionItem(id, connection)); await Map.ClientConnected(id); await SendTo(id, new SocketMessage("Id", id)); await KeepAlive(connection); await Map.ClientDisconnected(id); Connections.RemoveAll(c => c.Id == id); }
static async Task SendAsync(WebSocket ws, Message m) { using (MemoryStream mem = new MemoryStream()) using (StreamWriter sw = new StreamWriter(mem)) { await sw.WriteAsync(JsonConvert.SerializeObject(m)); await sw.FlushAsync(); var seg = new ArraySegment<byte>(mem.GetBuffer(), 0, (int)mem.Length); await ws.SendAsync(seg, WebSocketMessageType.Text, true, CancellationToken.None); } }
public WebSocketSession(WebSocket webSocket, DelegateGotMessage gotMessage, CompletionQueue completion_queue) { this.completion_queue = completion_queue; this.send_queue = new SendQueue(completion_queue, new WebsocketSendAsync(webSocket, completion_queue)); if (null == webSocket) throw new Exception("no websocket context"); this.webSocket = webSocket; if (null == gotMessage) throw new Exception("no recv message callback"); this.gotMessage = gotMessage; this._Id = Guid.NewGuid(); ReceiveAsyncLoop(); SendSessionId(); }
public MessageDispatcher( IOptions<ServerSettings> settings, IClientMessageFactory clientMessageFactory, WebSocket webSocket, Guid clientId, ClientType clientType) { _settings = settings; _clientMessageFactory = clientMessageFactory; _webSocket = webSocket; _clientId = clientId; _clientType = clientType; _createdDate = DateTime.Now; }
private static async Task PipeToWebSocketWorker(WebSocket socket, IMessagePipeEnd pipe, CancellationToken cancellationToken) { while (true) { cancellationToken.ThrowIfCancellationRequested(); byte[] message; try { message = await pipe.ReadAsync(cancellationToken); } catch (PipeDisconnectedException) { break; } await socket.SendAsync(new ArraySegment<byte>(message, 0, message.Length), WebSocketMessageType.Binary, true, cancellationToken); } }
internal WebSocketAdapter(WebSocket webSocket, CancellationToken ct) { _webSocket = webSocket; _cancellationToken = ct; _environment = new Dictionary<string, object>(); _environment[OwinConstants.WebSocket.SendAsync] = new WebSocketSendAsync(SendAsync); _environment[OwinConstants.WebSocket.ReceiveAsync] = new WebSocketReceiveAsync(ReceiveAsync); _environment[OwinConstants.WebSocket.CloseAsync] = new WebSocketCloseAsync(CloseAsync); _environment[OwinConstants.WebSocket.CallCancelled] = ct; _environment[OwinConstants.WebSocket.Version] = OwinConstants.WebSocket.VersionValue; _environment[typeof(WebSocket).FullName] = webSocket; }
internal OwinWebSocketWrapper(WebSocketContext context, CancellationToken ct) { _context = context; _webSocket = _context.WebSocket; _cancellationToken = ct; _environment = new Dictionary<string, object>(); _environment[Constants.WebSocketSendAsyncKey] = new WebSocketSendAsync(SendAsync); _environment[Constants.WebSocketReceiveAyncKey] = new WebSocketReceiveAsync(ReceiveAsync); _environment[Constants.WebSocketCloseAsyncKey] = new WebSocketCloseAsync(CloseAsync); _environment[Constants.WebSocketCallCancelledKey] = ct; _environment[Constants.WebSocketVersionKey] = Constants.WebSocketVersion; _environment[typeof(WebSocketContext).FullName] = _context; }
private async Task EchoWebSocket(WebSocket webSocket) { byte[] buffer = new byte[1024]; WebSocketReceiveResult received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); while (!webSocket.CloseStatus.HasValue) { // Echo anything we receive await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, received.Count), received.MessageType, received.EndOfMessage, CancellationToken.None); received = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); } await webSocket.CloseAsync(webSocket.CloseStatus.Value, webSocket.CloseStatusDescription, CancellationToken.None); }
public override void OnClose(string connectionGUID, System.Net.WebSockets.WebSocket socket) { WebSocketConnectionManager.RemoveSocket(connectionGUID, socket); ExecuteHandler(HandlerType.OnClose, new Object[] { connectionGUID }); OnSessionClosed?.Invoke(connectionGUID, string.Empty); }
WebSocketHandler(System.Net.WebSockets.WebSocket socket) { this._socket = socket; }
/// <summary> /// 部分Handler过程参考:http://www.cnblogs.com/lookbs/p/MVC-IMG.html /// </summary> /// <param name="webSocketContext"></param> /// <returns></returns> public static async Task WebSocketRequestHandler(AspNetWebSocketContext webSocketContext) { //Gets the current WebSocket object. System.Net.WebSockets.WebSocket webSocket = webSocketContext.WebSocket; /*We define a certain constant which will represent * size of received data. It is established by us and * we can set any value. We know that in this case the size of the sent * data is very small. */ const int maxMessageSize = 1024; //Buffer for received bits. var receivedDataBuffer = new ArraySegment <Byte>(new Byte[maxMessageSize]); var cancellationToken = new CancellationToken(); WebSocketHelper webSocketHandler = new WebSocketHelper(webSocketContext, cancellationToken); var messageHandler = WebSocketConfig.WebSocketMessageHandlerFunc.Invoke(); if (webSocket.State == WebSocketState.Connecting) { if (WebSocketConfig.WebSocketMessageHandlerFunc != null) { await messageHandler.OnConnecting(webSocketHandler);//调用MessageHandler } } //Checks WebSocket state. while (webSocket.State == WebSocketState.Open) { //Reads data. WebSocketReceiveResult webSocketReceiveResult = await webSocket.ReceiveAsync(receivedDataBuffer, cancellationToken); //If input frame is cancelation frame, send close command. if (webSocketReceiveResult.MessageType == WebSocketMessageType.Close) { if (WebSocketConfig.WebSocketMessageHandlerFunc != null) { await messageHandler.OnDisConnected(webSocketHandler);//调用MessageHandler } await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, String.Empty, cancellationToken); } else { byte[] payloadData = receivedDataBuffer.Array .Where(b => b != 0) .Take(webSocketReceiveResult.Count) .ToArray(); if (WebSocketConfig.WebSocketMessageHandlerFunc != null) { //Because we know that is a string, we convert it. string receiveString = //System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length); System.Text.Encoding.UTF8.GetString(payloadData, 0, payloadData.Length); try { ReceivedMessage receivedMessage; try { receivedMessage = new ReceivedMessage() { Message = receiveString// + " | 系统错误:" + e.Message }; receivedMessage = Newtonsoft.Json.JsonConvert.DeserializeObject <ReceivedMessage>(receiveString); } catch (Exception e) { receivedMessage = new ReceivedMessage() { Message = receiveString// + " | 系统错误:" + e.Message }; } await messageHandler.OnMessageReceiced(webSocketHandler, receivedMessage, receiveString);//调用MessageHandler } catch (Exception ex) { } } } } }
public WebSocker(System.Net.WebSockets.WebSocket socket, HttpContext context, string id = null) { Socket = socket; Id = id ?? Guid.NewGuid().ToString(); HttpContext = context; }
//wrapper method for obnoxious data send private static async Task SendCompleteMessageAsync <T>(WS.WebSocket Socket, DataTransmission <T> data) { await Socket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes($"{data.MessageType}={JsonConvert.SerializeObject(data.Message)}")), WS.WebSocketMessageType.Text, true, CancellationToken.None); }
/// <summary> /// WebSocketHelper /// </summary> /// <param name="webSocketContext"></param> /// <param name="cancellationToken"></param> public WebSocketHelper(AspNetWebSocketContext webSocketContext, CancellationToken cancellationToken) { _webSocketContext = webSocketContext; _webSocket = webSocketContext.WebSocket; _cancellationToken = cancellationToken; }
public abstract Task OnMessage(string connectionGuid, System.Net.WebSockets.WebSocket socket, WebSocketReceiveResult result, byte[] buffer);
public virtual async Task OnDisconnected(System.Net.WebSockets.WebSocket socket) { await WebSocketConnectionManager.RemoveSocket(WebSocketConnectionManager.GetId(socket)); }
public void AddSocket(System.Net.WebSockets.WebSocket socket) { _sockets.TryAdd(CreateConnectionId(), socket); }
public virtual void OnConnected(System.Net.WebSockets.WebSocket socket, string userId) { WebSocketConnectionManager.AddSocket(socket, userId); }
public Task SendStringAsync(System.Net.WebSockets.WebSocket websocket, string message, Encoding encoding, CancellationToken cancellationToken) { return(SendBytesAsync(websocket, encoding.GetBytes(message), cancellationToken)); }
public Task SendAsync(System.Net.WebSockets.WebSocket websocket, Func <byte[]> supplier, CancellationToken cancellationToken) { return(SendBytesAsync(websocket, supplier(), cancellationToken)); }
public override void OnOpen(string connectionGUID, System.Net.WebSockets.WebSocket socket) { WebSocketConnectionManager.AddSocket(connectionGUID, socket); ExecuteHandler(HandlerType.OnOpen, new Object[] { connectionGUID }); OnSessionConnected?.Invoke(connectionGUID); }
public void AddSocket(System.Net.WebSockets.WebSocket socket, string userId) { _sockets.TryAdd(userId, socket); }
/// <summary> /// Initializes a new instance of the <see cref="WebSocket"/> class. /// </summary> /// <param name="webSocket">The web socket.</param> public WebSocket(System.Net.WebSockets.WebSocket webSocket) { SystemWebSocket = webSocket; }
private static async Task Echo(System.Net.WebSockets.WebSocket webSocket) { WebSocketReceiveResult wResult; { //byte[] buffer = new byte[size]; //var buffer = new ArraySegment<byte>(new byte[8192]); State s = new State(); s.WebsocketID = ConnectInfo.webSocketID++; s.Ls = LoginState.empty; s.roomIndex = -1; s.mapRoadAndCrossMd5 = ""; removeWsIsNotOnline(); addWs(webSocket, s.WebsocketID); var carsNames = new string[] { "车1", "车2", "车3", "车4", "车5" }; var playerName = "玩家" + Math.Abs(DateTime.Now.GetHashCode() % 10000); //if(s.Ls== LoginState.) do { try { var returnResult = await ReceiveStringAsync(webSocket, webWsSize); wResult = returnResult.wr; Console.WriteLine($"receive from web:{returnResult.result}"); CommonClass.Command c = Newtonsoft.Json.JsonConvert.DeserializeObject <CommonClass.Command>(returnResult.result); switch (c.c) { case "MapRoadAndCrossMd5": { if (s.Ls == LoginState.empty) { MapRoadAndCrossMd5 mapRoadAndCrossMd5 = Newtonsoft.Json.JsonConvert.DeserializeObject <MapRoadAndCrossMd5>(returnResult.result); s.mapRoadAndCrossMd5 = mapRoadAndCrossMd5.mapRoadAndCrossMd5; } }; break; case "CheckSession": { if (s.Ls == LoginState.empty) { CheckSession checkSession = Newtonsoft.Json.JsonConvert.DeserializeObject <CheckSession>(returnResult.result); var checkResult = await BLL.CheckSessionBLL.checkIsOK(checkSession, s); if (checkResult.CheckOK) { s.Key = checkResult.Key; s.roomIndex = checkResult.roomIndex; s = await Room.setOnLine(s, webSocket); } else { s = await Room.setState(s, webSocket, LoginState.selectSingleTeamJoin); } } }; break; case "JoinGameSingle": { JoinGameSingle joinType = Newtonsoft.Json.JsonConvert.DeserializeObject <JoinGameSingle>(returnResult.result); if (s.Ls == LoginState.selectSingleTeamJoin) { s = await Room.GetRoomThenStart(s, webSocket, playerName, carsNames); } }; break; case "CreateTeam": { CreateTeam ct = Newtonsoft.Json.JsonConvert.DeserializeObject <CreateTeam>(returnResult.result); if (s.Ls == LoginState.selectSingleTeamJoin) { { string command_start; CommonClass.TeamResult team; { s = await Room.setState(s, webSocket, LoginState.WaitingToStart); } { // command_start = CommonClass.Random.GetMD5HashFromStr(s.WebsocketID.ToString() + s.WebsocketID); team = await Team.createTeam2(s.WebsocketID, playerName, command_start); } { //var command_start = CommonClass.Random.GetMD5HashFromStr(s.WebsocketID.ToString() + s.WebsocketID); returnResult = await ReceiveStringAsync(webSocket, webWsSize); wResult = returnResult.wr; if (returnResult.result == command_start) { s = await Room.GetRoomThenStartAfterCreateTeam(s, webSocket, team, playerName, carsNames); } else { return; } } } } }; break; case "JoinTeam": { JoinTeam ct = Newtonsoft.Json.JsonConvert.DeserializeObject <JoinTeam>(returnResult.result); if (s.Ls == LoginState.selectSingleTeamJoin) { { string command_start; { //将状态设置为等待开始和等待加入 s = await Room.setState(s, webSocket, LoginState.WaitingToGetTeam); } { returnResult = await ReceiveStringAsync(webSocket, webWsSize); wResult = returnResult.wr; var teamID = returnResult.result; command_start = CommonClass.Random.GetMD5HashFromStr(s.WebsocketID.ToString() + s.WebsocketID + DateTime.Now.ToString()); var result = await Team.findTeam2(s.WebsocketID, playerName, command_start, teamID); if (result == "ok") { returnResult = await ReceiveStringAsync(webSocket, webWsSize); wResult = returnResult.wr; int roomIndex; if (Room.CheckSecret(returnResult.result, command_start, out roomIndex)) { s = await Room.GetRoomThenStartAfterJoinTeam(s, webSocket, roomIndex, playerName, carsNames); } else { return; } } else if (result == "game has begun") { s = await Room.setState(s, webSocket, LoginState.selectSingleTeamJoin); await Room.Alert(webSocket, $"他们已经开始了!"); } else if (result == "is not number") { s = await Room.setState(s, webSocket, LoginState.selectSingleTeamJoin); await Room.Alert(webSocket, $"请输入数字"); } else if (result == "not has the team") { s = await Room.setState(s, webSocket, LoginState.selectSingleTeamJoin); await Room.Alert(webSocket, $"没有该队伍({teamID})"); } else if (result == "team is full") { s = await Room.setState(s, webSocket, LoginState.selectSingleTeamJoin); await Room.Alert(webSocket, "该队伍已满员"); } else { s = await Room.setState(s, webSocket, LoginState.selectSingleTeamJoin); } } } } }; break; case "SetCarsName": { if (s.Ls == LoginState.selectSingleTeamJoin) { SetCarsName setCarsName = Newtonsoft.Json.JsonConvert.DeserializeObject <SetCarsName>(returnResult.result); for (var i = 0; i < 5; i++) { if (!string.IsNullOrEmpty(setCarsName.Names[i])) { if (setCarsName.Names[i].Trim().Length >= 2 && setCarsName.Names[i].Trim().Length < 7) { carsNames[i] = setCarsName.Names[i].Trim(); } } } } }; break; case "GetCarsName": { if (s.Ls == LoginState.selectSingleTeamJoin) { var msg = Newtonsoft.Json.JsonConvert.SerializeObject(new { c = "GetCarsName", names = carsNames }); var sendData = Encoding.UTF8.GetBytes(msg); await webSocket.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), WebSocketMessageType.Text, true, CancellationToken.None); } }; break; case "SetPlayerName": { if (s.Ls == LoginState.selectSingleTeamJoin) { SetPlayerName setPlayerName = Newtonsoft.Json.JsonConvert.DeserializeObject <SetPlayerName>(returnResult.result); playerName = setPlayerName.Name; } }; break; case "GetName": { if (s.Ls == LoginState.selectSingleTeamJoin) { var msg = Newtonsoft.Json.JsonConvert.SerializeObject(new { c = "GetName", name = playerName }); var sendData = Encoding.UTF8.GetBytes(msg); await webSocket.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), WebSocketMessageType.Text, true, CancellationToken.None); } }; break; //case "SetCarName": // { // if (s.Ls == LoginState.selectSingleTeamJoin) // { // SetCarName setCarName = Newtonsoft.Json.JsonConvert.DeserializeObject<SetCarName>(returnResult.result); // if (setCarName.Name.Trim().Length < 7 && setCarName.Name.Trim().Length > 1) // { // if (setCarName.CarIndex >= 0 && setCarName.CarIndex < 5) // { // carsNames[setCarName.CarIndex] = setCarName.Name; // } // } // //playerName = setPlayerName.Name; // } // }; break; case "Promote": { if (s.Ls == LoginState.OnLine) { Promote promote = Newtonsoft.Json.JsonConvert.DeserializeObject <Promote>(returnResult.result); await Room.setPromote(s, promote); } }; break; case "Collect": { if (s.Ls == LoginState.OnLine) { Collect collect = Newtonsoft.Json.JsonConvert.DeserializeObject <Collect>(returnResult.result); await Room.setCollect(s, collect); } }; break; case "Attack": { if (s.Ls == LoginState.OnLine) { Attack attack = Newtonsoft.Json.JsonConvert.DeserializeObject <Attack>(returnResult.result); await Room.setAttack(s, attack); } }; break; case "Tax": { if (s.Ls == LoginState.OnLine) { Tax tax = Newtonsoft.Json.JsonConvert.DeserializeObject <Tax>(returnResult.result); await Room.setToCollectTax(s, tax); } }; break; case "Msg": { if (s.Ls == LoginState.OnLine) { Msg msg = Newtonsoft.Json.JsonConvert.DeserializeObject <Msg>(returnResult.result); if (msg.MsgPass.Length < 120) { await Room.passMsg(s, msg); } } }; break; case "Ability": { if (s.Ls == LoginState.OnLine) { Ability a = Newtonsoft.Json.JsonConvert.DeserializeObject <Ability>(returnResult.result); await Room.setCarAbility(s, a); } }; break; case "SetCarReturn": { if (s.Ls == LoginState.OnLine) { SetCarReturn scr = Newtonsoft.Json.JsonConvert.DeserializeObject <SetCarReturn>(returnResult.result); await Room.setCarReturn(s, scr); } }; break; case "Donate": { if (s.Ls == LoginState.OnLine) { Donate donate = Newtonsoft.Json.JsonConvert.DeserializeObject <Donate>(returnResult.result); await Room.Donate(s, donate); } }; break; case "GetSubsidize": { if (s.Ls == LoginState.OnLine) { GetSubsidize getSubsidize = Newtonsoft.Json.JsonConvert.DeserializeObject <GetSubsidize>(returnResult.result); await Room.GetSubsidize(s, getSubsidize); } }; break; case "OrderToSubsidize": { if (s.Ls == LoginState.OnLine) { GetSubsidize getSubsidize = Newtonsoft.Json.JsonConvert.DeserializeObject <GetSubsidize>(returnResult.result); await Room.GetSubsidize(s, getSubsidize); } }; break; case "Bust": { if (s.Ls == LoginState.OnLine) { Bust bust = Newtonsoft.Json.JsonConvert.DeserializeObject <Bust>(returnResult.result); await Room.setBust(s, bust); } }; break; case "BuyDiamond": { if (s.Ls == LoginState.OnLine) { BuyDiamond bd = Newtonsoft.Json.JsonConvert.DeserializeObject <BuyDiamond>(returnResult.result); await Room.buyDiamond(s, bd); } }; break; case "SellDiamond": { if (s.Ls == LoginState.OnLine) { BuyDiamond bd = Newtonsoft.Json.JsonConvert.DeserializeObject <BuyDiamond>(returnResult.result); await Room.sellDiamond(s, bd); } }; break; case "DriverSelect": { if (s.Ls == LoginState.OnLine) { DriverSelect ds = Newtonsoft.Json.JsonConvert.DeserializeObject <DriverSelect>(returnResult.result); await Room.selectDriver(s, ds); } }; break; case "Skill1": { if (s.Ls == LoginState.OnLine) { Skill1 s1 = Newtonsoft.Json.JsonConvert.DeserializeObject <Skill1>(returnResult.result); await Room.magic(s, s1); } }; break; case "Skill2": { if (s.Ls == LoginState.OnLine) { Skill2 s2 = Newtonsoft.Json.JsonConvert.DeserializeObject <Skill2>(returnResult.result); await Room.magic(s, s2); } }; break; case "ViewAngle": { if (s.Ls == LoginState.OnLine) { ViewAngle va = Newtonsoft.Json.JsonConvert.DeserializeObject <ViewAngle>(returnResult.result); await Room.view(s, va); } }; break; } } catch (Exception e) { Console.WriteLine($"{ Newtonsoft.Json.JsonConvert.SerializeObject(e)}"); await Room.setOffLine(s); removeWs(s.WebsocketID); // Console.WriteLine($"step2:webSockets数量:{ BufferImage.webSockets.Count}"); // return; throw e; } }while (!wResult.CloseStatus.HasValue); await Room.setOffLine(s); removeWs(s.WebsocketID); //try //{ // // await webSocket.CloseAsync(wResult.CloseStatus.Value, wResult.CloseStatusDescription, CancellationToken.None); // // ConnectInfo.connectedWs.Remove(c.WebSocketID); //} //catch (Exception e) //{ // throw e; // // ConnectInfo.connectedWs.Remove(c.WebSocketID); // // return; //} }; }
public virtual void OnClose(string connectionGuid, System.Net.WebSockets.WebSocket socket) { }
private Handler(WS.WebSocket socket) { Socket = socket; }
public string GetId(System.Net.WebSockets.WebSocket socket) { return(_sockets.FirstOrDefault(p => p.Value == socket).Key); }
public static IChannel Create(WebSocketConfig config, HttpContext context, System.Net.WebSockets.WebSocket socket, CancellationToken token) { return(WebSocketChannel.Create(context, socket, config, token)); }
public SystemWebSocket(System.Net.WebSockets.WebSocket webSocket) { UnderlyingWebSocket = webSocket; }
//private static Task dealWithNotify(WebSocket webSocket) //{ // throw new NotImplementedException(); //} private static async Task dealWithNotify(System.Net.WebSockets.WebSocket webSocketFromGameRoom) { throw new Exception(""); WebSocketReceiveResult wResult; { // do { try { var returnResult = await ReceiveStringAsync(webSocketFromGameRoom, webWsSize); wResult = returnResult.wr; // Console.WriteLine($"receive:{returnResult.result}"); var notifyJson = returnResult.result; Console.WriteLine($"notify receive:{notifyJson}"); CommonClass.CommandNotify c = Newtonsoft.Json.JsonConvert.DeserializeObject <CommonClass.CommandNotify>(notifyJson); // CommonClass.TeamCreateFinish teamCreateFinish = Newtonsoft.Json.JsonConvert.DeserializeObject<CommonClass.TeamCreateFinish>(notifyJson); WebSocket ws = null; lock (ConnectInfo.connectedWs_LockObj) { if (ConnectInfo.connectedWs.ContainsKey(c.WebSocketID)) { if (ConnectInfo.connectedWs[c.WebSocketID].State == WebSocketState.Open) { ws = ConnectInfo.connectedWs[c.WebSocketID]; } else { ConnectInfo.connectedWs.Remove(c.WebSocketID); } } } // await context.Response.WriteAsync("ok"); if (ws != null) { if (ws.State == WebSocketState.Open) { try { var sendData = Encoding.UTF8.GetBytes(notifyJson); await ws.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), WebSocketMessageType.Text, true, CancellationToken.None); await ws.CloseAsync(WebSocketCloseStatus.Empty, null, CancellationToken.None); } catch { } } } } catch { // Console.WriteLine($"step2:webSockets数量:{ BufferImage.webSockets.Count}"); return; } } //while (!wResult.CloseStatus.HasValue); //try //{ // await webSocketFromGameRoom.CloseAsync(wResult.CloseStatus.Value, wResult.CloseStatusDescription, CancellationToken.None); //} //catch //{ // return; //} }; }
private static async Task Echo(System.Net.WebSockets.WebSocket webSocket) { WebSocketReceiveResult wResult; { byte[] buffer = new byte[size]; do { try { wResult = await webSocket.ReceiveAsync(new ArraySegment <byte>(buffer), CancellationToken.None); var str = getStrFromByte(ref buffer); if (str == "allMap") { Dictionary <string, bool> Cs = new Dictionary <string, bool>(); List <object> listOfCrosses = new List <object>(); Dictionary <string, Dictionary <int, OssModel.SaveRoad.RoadInfo> > result; Program.dt.GetData(out result); List <double[]> meshPoints = new List <double[]>(); // List<int> colors = new List<int>(); foreach (var item in result) { foreach (var itemj in item.Value) { var value = itemj.Value; var ps = getRoadRectangle(value, item.Value); meshPoints.Add(ps); for (var i = 0; i < value.Cross1.Length; i++) { var cross = value.Cross1[i]; var key = cross.RoadCode1.CompareTo(cross.RoadCode2) > 0 ? $"{cross.RoadCode1}_{cross.RoadOrder1}_{cross.RoadCode2}_{cross.RoadOrder2}" : $"{cross.RoadCode2}_{cross.RoadOrder2}_{cross.RoadCode1}_{cross.RoadOrder1}"; if (Cs.ContainsKey(key)) { } else { Cs.Add(key, false); listOfCrosses.Add(new { lon = cross.BDLongitude, lat = cross.BDLatitude, state = cross.CrossState }); } } //value.Cross1 } } { var msg = Newtonsoft.Json.JsonConvert.SerializeObject(new { reqMsg = str, t = "road", obj = meshPoints }); var sendData = Encoding.UTF8.GetBytes(msg); await webSocket.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), wResult.MessageType, true, CancellationToken.None); } { var msg = Newtonsoft.Json.JsonConvert.SerializeObject(new { reqMsg = str, t = "cross", obj = listOfCrosses }); var sendData = Encoding.UTF8.GetBytes(msg); await webSocket.SendAsync(new ArraySegment <byte>(sendData, 0, sendData.Length), wResult.MessageType, true, CancellationToken.None); } //foreach (var item in result) //{ // foreach (var itemj in item.Value) // { // var value = itemj.Value; // var ps = getCrossPoints(value, result); // meshPoints.Add(ps); // } //} } } catch { // Console.WriteLine($"step2:webSockets数量:{ BufferImage.webSockets.Count}"); return; } }while (!wResult.CloseStatus.HasValue); try { await webSocket.CloseAsync(wResult.CloseStatus.Value, wResult.CloseStatusDescription, CancellationToken.None); } catch { return; } }; }
//private Thread thread;//工作线程 public WebSocket(HttpContext context, System.Net.WebSockets.WebSocket webSocket, IWebsocketProcessor processor) { this.Context = context; this.Socket = webSocket; this.Processor = processor; }
/// <summary> /// WebSocketHelper /// </summary> ///// <param name="webSocketContext"></param> /// <param name="cancellationToken"></param> #if NET451 public WebSocketHelper(System.Net.WebSockets.WebSocket socket, /*AspNetWebSocketContext webSocketContext,*/ CancellationToken cancellationToken) { WebSocket = socket;
public NetWebSocket(System.Net.WebSockets.WebSocket webSocket) { mWebSocket = webSocket; mSendQueue = new TaskQueue(); }
/// <summary> /// 进行聊天 /// </summary> /// <param name="context">AspNetWebSocket上下文</param> /// <param name="userName">用户昵称</param> /// <returns></returns> public async Task ProcessChat(AspNetWebSocketContext context, string userName) { System.Net.WebSockets.WebSocket socket = context.WebSocket; try { #region 用户添加连接池 //第一次 Open 时,添加到连接池中 if (!CONNECT_POOL.ContainsKey(userName)) { CONNECT_POOL.Add(userName, socket);//不存在,添加 } else if (socket != CONNECT_POOL[userName]) //当前对象不一致,更新 { CONNECT_POOL[userName] = socket; } #endregion 用户添加连接池 #region 离线消息处理 if (MESSAGE_POOL.ContainsKey(userName)) { List <MessageInfo> msgs = MESSAGE_POOL[userName]; foreach (MessageInfo item in msgs) { string msgTime = item.MsgTime.ToString("yyyy年MM月dd日HH:mm:ss"); string msgContent = Encoding.UTF8.GetString(item.MsgContent.Array); await socket.SendAsync(new ArraySegment <byte>(Encoding.UTF8.GetBytes("时间:" + msgTime + "内容:" + msgContent)), WebSocketMessageType.Text, true, CancellationToken.None); } MESSAGE_POOL.Remove(userName);//移除离线消息 } #endregion 离线消息处理 string descUser = string.Empty;//目的用户 while (true) { if (socket.State == WebSocketState.Open) { ArraySegment <byte> buffer = new ArraySegment <byte>(new byte[2048]); WebSocketReceiveResult result = await socket.ReceiveAsync(buffer, CancellationToken.None); #region 消息处理(字符截取、消息转发) try { #region 关闭Socket处理,删除连接池 if (socket.State != WebSocketState.Open)//连接关闭 { if (CONNECT_POOL.ContainsKey(userName)) { CONNECT_POOL.Remove(userName); //删除连接池 } break; } #endregion 关闭Socket处理,删除连接池 string userMsg = Encoding.UTF8.GetString(buffer.Array, 0, result.Count);//发送过来的消息 string[] msgList = userMsg.Split('|'); if (msgList.Length == 2) { if (msgList[0].Trim().Length > 0) { descUser = msgList[0].Trim();//记录消息目的用户 } buffer = new ArraySegment <byte>(Encoding.UTF8.GetBytes(msgList[1])); if (CONNECT_POOL.ContainsKey(descUser)) //判断客户端是否在线 { System.Net.WebSockets.WebSocket destSocket = CONNECT_POOL[descUser]; //目的客户端 if (destSocket != null && destSocket.State == WebSocketState.Open) { await destSocket.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } } else { await Task.Run(() => { if (!MESSAGE_POOL.ContainsKey(descUser))//将用户添加至离线消息池中 { MESSAGE_POOL.Add(descUser, new List <MessageInfo>()); } MESSAGE_POOL[descUser].Add(new MessageInfo(DateTime.Now, buffer));//添加离线消息 }); } } else { buffer = new ArraySegment <byte>(Encoding.UTF8.GetBytes(userMsg)); foreach (KeyValuePair <string, System.Net.WebSockets.WebSocket> item in CONNECT_POOL) { await item.Value.SendAsync(buffer, WebSocketMessageType.Text, true, CancellationToken.None); } } } catch (Exception exs) { //消息转发异常处理,本次消息忽略 继续监听接下来的消息 string message = exs.Message; } #endregion 消息处理(字符截取、消息转发) } else { break; } } } catch (Exception ex) { string message = ex.Message; //整体异常处理 if (CONNECT_POOL.ContainsKey(userName)) { CONNECT_POOL.Remove(userName); } } }
public static async Task <ReceiveObj> ReceiveStringAsync(System.Net.WebSockets.WebSocket socket, CancellationToken ct = default(CancellationToken)) { return(await ReceiveStringAsync(socket, webWsSize)); }
public static IApplicationBuilder UseDebugProxy( this IApplicationBuilder app, ProxyOptions options, Func <Dictionary <string, string>, HttpContext, Uri, Dictionary <string, string> > mapFunc) { Uri devToolsHost = options.DevToolsUrl; app.UseRouter(router => { router.MapGet("/", Copy); router.MapGet("/favicon.ico", Copy); router.MapGet("json", RewriteArray); router.MapGet("json/list", RewriteArray); router.MapGet("json/version", RewriteSingle); router.MapGet("json/new", RewriteSingle); router.MapGet("devtools/page/{pageId}", ConnectProxy); router.MapGet("devtools/browser/{pageId}", ConnectProxy); string GetEndpoint(HttpContext context) { HttpRequest request = context.Request; PathString requestPath = request.Path; return($"{devToolsHost.Scheme}://{devToolsHost.Authority}{request.Path}{request.QueryString}"); } async Task Copy(HttpContext context) { using (var httpClient = new HttpClient { Timeout = TimeSpan.FromSeconds(5) }) { HttpResponseMessage response = await httpClient.GetAsync(GetEndpoint(context)); context.Response.ContentType = response.Content.Headers.ContentType.ToString(); if ((response.Content.Headers.ContentLength ?? 0) > 0) { context.Response.ContentLength = response.Content.Headers.ContentLength; } byte[] bytes = await response.Content.ReadAsByteArrayAsync(); await context.Response.Body.WriteAsync(bytes); } } async Task RewriteSingle(HttpContext context) { Dictionary <string, string> version = await ProxyGetJsonAsync <Dictionary <string, string> >(GetEndpoint(context)); context.Response.ContentType = "application/json"; await context.Response.WriteAsync( JsonSerializer.Serialize(mapFunc(version, context, devToolsHost))); } async Task RewriteArray(HttpContext context) { Dictionary <string, string>[] tabs = await ProxyGetJsonAsync <Dictionary <string, string>[]>(GetEndpoint(context)); Dictionary <string, string>[] alteredTabs = tabs.Select(t => mapFunc(t, context, devToolsHost)).ToArray(); context.Response.ContentType = "application/json"; await context.Response.WriteAsync(JsonSerializer.Serialize(alteredTabs)); } async Task ConnectProxy(HttpContext context) { if (!context.WebSockets.IsWebSocketRequest) { context.Response.StatusCode = 400; return; } var endpoint = new Uri($"ws://{devToolsHost.Authority}{context.Request.Path}"); int runtimeId = 0; if (context.Request.Query.TryGetValue("RuntimeId", out StringValues runtimeIdValue) && int.TryParse(runtimeIdValue.FirstOrDefault(), out int parsedId)) { runtimeId = parsedId; } try { using ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddSimpleConsole(options => { options.SingleLine = true; options.TimestampFormat = "[HH:mm:ss] "; }) .AddFilter(null, LogLevel.Information) ); context.Request.Query.TryGetValue("urlSymbolServer", out StringValues urlSymbolServerList); var proxy = new DebuggerProxy(loggerFactory, urlSymbolServerList.ToList(), runtimeId); System.Net.WebSockets.WebSocket ideSocket = await context.WebSockets.AcceptWebSocketAsync(); await proxy.Run(endpoint, ideSocket); } catch (Exception e) { Console.WriteLine("got exception {0}", e); } } }); return(app); }
public async Task <T> ReadAsync <T>(System.Net.WebSockets.WebSocket websocket, Func <byte[], T> mapper, CancellationToken cancellationToken) { var data = await ReadBytesAsync(websocket, cancellationToken); return(mapper(data)); }