问题描述
- .net websocket 实现 报错
- Error during WebSocket handshake: Unexpected response code: 200
chrome控制台报的错误
action代码public HttpResponseMessage T() { if (System.Web.HttpContext.Current.IsWebSocketRequest) { System.Web.HttpContext.Current.AcceptWebSocketRequest(ProcessWSChat); } return new HttpResponseMessage(HttpStatusCode.SwitchingProtocols); //return View(); } private async Task ProcessWSChat(AspNetWebSocketContext context) { System.Net.WebSockets.WebSocket socket = context.WebSocket; while (true) { //ArraySegment<byte> buffer = new ArraySegment<byte>(new byte[1024]); //WebSocketReceiveResult result = await socket.ReceiveAsync( // buffer CancellationToken.None); if (socket.State == WebSocketState.Open) { //string userMessage = Encoding.UTF8.GetString( // buffer.Array 0 result.Count); string userMessage = DateTime.Now.ToString(); ArraySegment<byte> buffer = new ArraySegment<byte>( Encoding.UTF8.GetBytes(userMessage)); await socket.SendAsync( buffer WebSocketMessageType.Text true CancellationToken.None); } else { break; } } }
js代码
<script type=""text/javascript""> var serverDatastatusDivws; //var SERVER_URL = ""/Dou/T""; window.onload = function () { ws = new WebSocket(""ws://"" + window.location.host + ""/Sun/T""); serverData = document.getElementById(""serverData""); statusDiv = document.getElementById(""statusDiv""); startlistenServer(); } function startlistenServer() { statusDiv.innerHTML=""Start Connect Server...""; //var es = new EventSource(SERVER_URL); ws.onopen = openHandler; ws.onerror = errorHandler; ws.onmessage = messageHandler; } function openHandler(e) { statusDiv.innerHTML = ""Server Open<br>""; } function errorHandler(e) { statusDiv.innerHTML = ""Error<br>""+e.message; } function messageHandler(e) { serverData.innerHTML = e.data; }</script>
解决方案
你确定HttpContext.Current 这个没错
时间: 2024-12-22 07:39:41