C#Tcp服务器-HTML5网络套接字通信

本文关键字:套接字 通信 网络 -HTML5 服务器 C#Tcp | 更新日期: 2023-09-27 18:20:08

我正在编写C#Tcp服务器和HTML5 Websocket客户端。但当从客户端向服务器发送消息时,我在C#Tcp服务器上得到了"GET/HTTP/1.1"消息。

c#服务器

using System;using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.IO;
namespace websocket
{
    class Program
    {
        static void Main(string[] args)
        {
            TcpListener server = new TcpListener(IPAddress.Parse("127.0.0.2"), 500);
            server.Start();
            Console.WriteLine("Basladi");
            Console.WriteLine("Bekliyor");
            while (true)
            {
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Baglandi");
                NetworkStream asd = client.GetStream();
                byte[] buffer = new byte[1024];
                String mesaj = Encoding.ASCII.GetString(buffer, 0, asd.Read(buffer, 0, buffer.Length));
                Console.WriteLine(mesaj);
            }
            server.Stop();
        }
    }
}

HTML5 Websocket客户端

function WebSocketTest()
{
     var ws = new WebSocket("ws://127.0.0.2:500");
     ws.onopen = function()
     {
        ws.send("Message to send");
        document.write("Message is sent...");
     };
     ws.onmessage = function (evt) 
     { 
        var received_msg = evt.data;
        document.write("Message is received...");
     };
     ws.onclose = function()
     { 
        document.write("Connection is closed..."); 
     };
}

结果

GET / HTTP/1.1
Upgrade: websocket
Connection: Upgrade
Host: 127.0.0.2:500
Origin: null
Pragma: no-cache
Cache-Control: no-cache
Sec-WebSocket-Key: Nmh4m9EiHa9GFx8Ft5Z9bQ==
Sec-WebSocket-Version: 13
Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits, x-webkit-deflate-frame
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.143 Safari/537.36

C#Tcp服务器-HTML5网络套接字通信

WebSockets不是普通的TCP套接字,而是HTTP连接中的类似套接字的层。您在这里看到的是客户端的HTTP请求,其中包含将HTTP连接升级为WebSocket连接的请求。如果你不想使用现有的WebSocket库,你必须自己实现协议,即首先实现一个最小的web服务器(RFC2616),然后将WebSocket层放在上面(RFC6455)。