C#Websocket服务器无法从HTML5客户端

时间:2017-11-17 02:01:53

标签: c# html5 websocket

我试图创建一个裸骨架websocket聊天室服务器。我的客户端能够连接到服务器,但它无法向服务器发送消息,尽管服务器处于侦听状态。

当客户端连接时,一堆看起来像头信息的内容会写入控制台。但是当WebSocket.send()在Javascript中执行时,服务器端就不会发生任何事情。

HTML:

<button id="closeSocket">disconnect</button><br />
<input id = "inputField" /><button id="sendMessage">send</button>
<div id = "output"></div>

<script type = 'text/javascript' src = 'websockets.js'></script>

使用Javascript:

websocket = new WebSocket("ws://127.0.0.1:80");

document.getElementById("closeSocket").onclick = closeSocket;
document.getElementById("sendMessage").onclick = sendMessage;

websocket.onopen = function(){
  output("connected");
}

function sendMessage(){
    output("sent: " + document.getElementById('inputField').value);
  websocket.send(document.getElementById('inputField').value);
}

websocket.onmessage = function(e){
  output("got response: " + e.data);
}

function closeSocket(){
    websocket.close();
}

websocket.onclose = function(){
    output("disconnected");
}

function output(t){
    document.getElementById("output").innerHTML += t + "<br />";
}

C#server:

using System;
using System.Net;
using System.Net.Sockets;

namespace WebSocketsTutorial {
    class Program {
        static void Main(string[] args) {
            TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
            TcpClient client = default(TcpClient);

            server.Start();
            Console.WriteLine("server started");

            while (true) {
                client = server.AcceptTcpClient();

                byte[] receivedBuffer = new byte[100];
                NetworkStream stream = client.GetStream();

                stream.Read(receivedBuffer, 0, receivedBuffer.Length);

                foreach (byte b in receivedBuffer) {
                    Console.Write(Convert.ToChar(b).ToString());
                }
            }
        }
    }
}

这是客户端连接时在控制台上输出的内容:

enter image description here

我主要想做的是允许任意数量的连接,并最终让服务器回应用户提交给所有连接的客户端。

1 个答案:

答案 0 :(得分:0)

首先,WebSocket不仅仅是一个普通的套接字。它使用HTTP和您自己需要使用的成帧协议定义连接握手。

https://en.wikipedia.org/wiki/WebSocket

https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers

https://hpbn.co/websocket/

其次,您只读取请求的前100个字节。您应该阅读,直到Read操作返回0。

您可以使用无数组件来创建WebSocket服务器,包括默认组件:https://docs.microsoft.com/en-us/aspnet/core/fundamentals/websockets