我不明白为什么我不能使下面的代码工作。我想用 JavaScript 连接到我的服务器控制台应用。然后将数据发送到服务器。
以下是服务器代码:
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 9998);
server.Start();
var client = server.AcceptTcpClient();
var stream = client.GetStream();
while (true)
{
var buffer = new byte[1024];
// wait for data to be received
var bytesRead = stream.Read(buffer, 0, buffer.Length);
var r = System.Text.Encoding.UTF8.GetString(buffer);
// write received data to the console
Console.WriteLine(r.Substring(0, bytesRead));
}
}
这是 JavaScript:
var ws = new WebSocket("ws://localhost:9998/service");
ws.onopen = function () {
ws.send("Hello World"); // I WANT TO SEND THIS MESSAGE TO THE SERVER!!!!!!!!
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function () {
// websocket is closed.
alert("Connection is closed...");
};
当我运行这段代码时,会发生以下情况:
请注意,当我运行 JavaScript 时,服务器接受并成功建立连接。但是 JavaScript 不能发送数据。无论何时我放置 send 方法,即使建立了连接,它也不会发送。我该怎么做?