我目前正在測試一些基本的websocket示例,這些示例並不完全幫助我理解基本知識。我瞭解如何使用C#在服務器上創建偵聽器,並將請求升級爲Web套接字。我需要幫助檢索從JavaScript發送到服務器的字符串。C#websocket服務器接收來自javascript的文本
C#代碼:
class Program
{
private static void ThreadProc(object obj)
{
var client = (TcpClient)obj;
var address = client.Client.RemoteEndPoint.ToString().Split(':');
Console.WriteLine(String.Format("A client is connected from {0}", address[0]));
NetworkStream stream = client.GetStream();
//enter to an infinite cycle to be able to handle every change in stream
while (true)
{
while (!stream.DataAvailable) ;
Byte[] bytes = new Byte[client.Available];
stream.Read(bytes, 0, bytes.Length);
//translate bytes of request to string
String data = Encoding.UTF8.GetString(bytes);
if (new Regex("^GET").IsMatch(data))
{
Byte[] response = Encoding.UTF8.GetBytes("HTTP/1.1 101 Switching Protocols" + Environment.NewLine
+ "Connection: Upgrade" + Environment.NewLine
+ "Upgrade: websocket" + Environment.NewLine
+ "Sec-WebSocket-Accept: " + Convert.ToBase64String(
SHA1.Create().ComputeHash(
Encoding.UTF8.GetBytes(
new Regex("Sec-WebSocket-Key: (.*)").Match(data).Groups[1].Value.Trim() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
)
)
) + Environment.NewLine
+ Environment.NewLine);
stream.Write(response, 0, response.Length);
}
else
{
Console.WriteLine(data);
}
}
}
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.1"), 80);
server.Start();
Console.WriteLine("Server has started on 127.0.0.1:80.{0}Waiting for a connection...", Environment.NewLine);
while (true)
{
var clientConnection = server.AcceptTcpClient();
ThreadPool.QueueUserWorkItem(ThreadProc, clientConnection);
}
}
}
JavaScript來連接到WebSocket的。
var host = window.location.origin.replace("http", "ws");
var socket = new WebSocket("ws://127.0.0.1:80");
socket.onopen = function (openEvent) {
console.log("Socket connection is open.");
sendTextMessage();
};
function sendTextMessage() {
if (socket.readyState != WebSocket.OPEN)
{
console.log("Socket is not open for connection.");
return;
}
socket.send("MDN");
}
更新我可以看到現在的消息來了。但是,我沒有得到字符串MDN我得到一些時髦的人物回來。更新我的C#代碼以顯示更改。
我只是簡單地試圖從我的JavaScript發送一個字符串到我的服務器,並在控制檯上讀取該字符串。如果任何人都可以解釋更多如何在同一時間連接多個網頁瀏覽器,那將是非常棒的。此外,如果任何人都可以指向我發送消息回所有連接的Web瀏覽器請做。
如果這是重複的,請指向正確的方向。
我遇到了同樣的問題,本文後面的函數DecodeMessage幫助了我:http://stackoverflow.com/questions/34372639/sending-a-message-back-to-client-using-tcplistener-server/34372944 –
實際上,我在這段代碼中遇到了很多問題,在研究了現在使用SignalR之後,這個例子幫了我很大忙:https://code.msdn.microsoft.com/windowsdesktop/Using-SignalR-in-WinForms- f1ec847b –