简体   繁体   English

C#Tcp服务器-HTML5 Websocket通信

[英]C# Tcp Server - HTML5 Websocket communication

I'm writing C# Tcp Server and HTML5 Websocket Client. 我正在编写C#Tcp Server和HTML5 Websocket Client。 But when sending message from client to server, I'm getting "GET/HTTP/1.1" message on C# Tcp Server. 但是,当从客户端向服务器发送消息时,我在C#Tcp服务器上收到“ GET / HTTP / 1.1”消息。

c# Server 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 Client 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..."); 
     };
}

Result 结果

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

WebSockets are not plain TCP sockets, but an socket-like layer inside an HTTP(s) connection. WebSocket不是普通的TCP套接字,而是HTTP连接中类似套接字的层。 What you see here is the HTTP request of the client with the request to upgrade the HTTP connection to a WebSocket connection. 您在此处看到的是客户端的HTTP请求,以及将HTTP连接升级到WebSocket连接的请求。 If you don't want to use existing WebSocket libraries you have to implement the protocol yourself, that is first implement a minimal web server (RFC2616) and then put the WebSocket layer on top (RFC6455). 如果您不想使用现有的WebSocket库,则必须自己实现该协议,即首先实现最小的Web服务器(RFC2616),然后将WebSocket层置于顶层(RFC6455)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM