私は WebSocket API の初心者です。サーバーにローカルで接続しようとしていますが、接続が閉じられたというメッセージが表示されます。誰が私が間違っているのか教えてもらえますか?
それが私のコードです:
サーバ
using System.Net.Sockets;
using System.Net;
using System.IO;
using System;
class Program
{
static void Main(string[] args)
{
var listener = new TcpListener(IPAddress.Loopback, 8181);
listener.Start();
while (true)
{
Console.WriteLine("Listening...");
using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
using (var reader = new StreamReader(stream))
using (var writer = new StreamWriter(stream))
{
string line = null, key = "", responseKey = "";
string MAGIC_STRING = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
while (line != "")
{
line = reader.ReadLine();
if (line.StartsWith("Sec-WebSocket-Key:"))
{
key = line.Split(':')[1].Trim();
}
}
if (key != "")
{
key += MAGIC_STRING;
using (var sha1 = SHA1.Create())
{
responseKey = Convert.ToBase64String(sha1.ComputeHash(Encoding.ASCII.GetBytes(key)));
}
}
// send handshake to the client
writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
writer.WriteLine("Upgrade: WebSocket");
writer.WriteLine("Connection: Upgrade");
writer.WriteLine("WebSocket-Origin: http://localhost:8080");
writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
if (!String.IsNullOrEmpty(responseKey))
writer.WriteLine("Sec-WebSocket-Accept: " + responseKey);
writer.WriteLine("");
Console.ReadLine();
writer.Flush();
}//using
Console.WriteLine("Finished");
}//while
}
}
クライアント
<!DOCTYPE HTML>
<html>
<head><title></title>
<script type="text/javascript">
function WebSocketTest() {
var msg = document.getElementById("msg");
if ("WebSocket" in window) {
msg.innerHTML="WebSocket is supported by your Browser!";
// Let us open a web socket
var ws = new WebSocket("ws://localhost:8181/websession");
ws.onopen = function () {
// Web Socket is connected, send data using send()
msg.innerHTML="connection open";
//ws.send("Message to send");
//msg.innerHTML="Message is sent...";
};
ws.onclose = function () {
// websocket is closed.
msg.innerHTML = "Connection is closed...";
};
ws.onerror = function(error){
console.log('Error detected: ' + error);
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
msg.innerHTML="Message is received...";
};
}
else {
// The browser doesn't support WebSocket
msg.innerHTML="WebSocket NOT supported by your Browser!";
}
}
</script>
</head>
<body>
<div id="sse">
<a href="javascript:WebSocketTest()">Run WebSocket</a><br />
<p id="msg"></p>
</div>
</body>
</html>
任意の解決策をいただければ幸いです。ありがとうございます:)