在从浏览器到C#程序的请求连接之后,没有来自WebSocket的响应

时间:2016-08-03 11:58:51

标签: javascript c# html5 tcp websocket

我正在学习如何让我的C#程序与浏览器进行通信。 我在我的HTML5浏览器中使用C#和WebSocket中的TCP。

C#

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;

namespace ShouldWork
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        TCPServer server = new TCPServer();
        System.Threading.Thread obj_thread = new System.Threading.Thread(server.startServer);
        obj_thread.Start();
    }

    private void textBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void button2_Click(object sender, EventArgs e)
    {
        TcpClient client = new TcpClient("127.0.0.1", 7000);
        NetworkStream ns = client.GetStream();
        byte[] data_tosend = createDataPacket(Encoding.UTF8.GetBytes(tx_data_send.Text));
        ns.Write(data_tosend, 0, data_tosend.Length);
    }

    private byte[] createDataPacket(byte[] data)
    {
        byte[] initialize = new byte[1];
        initialize[0] = 2;
        byte[] separator = new byte[1];
        separator[0] = 4;
        byte[] datalength = Encoding.UTF8.GetBytes(Convert.ToString(data.Length));
        MemoryStream ms = new MemoryStream();
        ms.Write(initialize, 0, initialize.Length);
        ms.Write(datalength, 0, datalength.Length);
        ms.Write(separator, 0, separator.Length);
        ms.Write(data, 0, data.Length);
        return ms.ToArray();
    }
}

class TCPServer
{
    TcpListener listener;
    public TCPServer()
    {
        listener = new TcpListener(IPAddress.Any, 7000);
    }

    public void startServer()
    {
        listener.Start();
        while (true)
        {
            TcpClient client = listener.AcceptTcpClient();
            NetworkStream ns = client.GetStream();
            if(ns.ReadByte() == 2)
            {
                byte[] recv_data = readStream(ns);
                Form1.ActiveForm.Invoke(new MethodInvoker(delegate
                {
                    ((TextBox)Form1.ActiveForm.Controls.Find("tx_recv_data", true)[0]).Text = Encoding.UTF8.GetString(recv_data);
                }));
            }
        }
    }

    public byte[] readStream(NetworkStream ns)
    {
        byte[] data_buff = null;

        int b = 0;
        String buff_length = "";

        while ((b = ns.ReadByte()) != 4)
        {
            buff_length += (char)b;
        }
        int data_length = Convert.ToInt32(buff_length);
        data_buff = new byte[data_length];
        int byte_read = 0;
        int byte_offset = 0;
        while (byte_offset < data_length)
        {
            byte_read = ns.Read(data_buff, byte_offset, data_length - byte_offset);
            byte_offset += byte_read;
        }

        return data_buff;
    }
}
}

UI

当用户单击“启动服务器”按钮时,程序将启动TCPServer。然后我们可以在第二个文本框中输入一些文本,然后我的代码将处理它并在第一个文本框中显示消息。

UI

现在我想将客户端部分移动到浏览器,因此我创建了一个简单的Web应用程序并测试了连接。

代码段

<!DOCTYPE html>
<html>
<head>
  <title>Socket demo</title>
</head>

<body>
  <button type="button" onclick="testWebSocket()">Connect to C# server</button><br><br>

  <script language="javascript" type="text/javascript">
    function testWebSocket(){

  var socket = new WebSocket('ws://127.0.0.1:7000');
  console.log("ssss");

  socket.onopen = function(){
    console.log("on open");
    socket.send("Hello");
  }

  socket.onclose = function(evt){
    console.log("on close");
  }

  socket.onerror = function(evt){
    console.log("on error");
    console.log(evt.data);
  }
}

  </script>
</body>
</html>

这是错误的...... onopen功能似乎根本不起作用,chrome控制台确实显示&#34; sss&#34;那就是......

我使用的方法有问题吗?

1 个答案:

答案 0 :(得分:0)

如评论中所示,WebSocket使用自己的框架架构。

请看一下这个链接:https://hpbn.co/websocket/,特别是解释框架的部分:https://hpbn.co/websocket/#binary-framing-layer

连接永远不会打开的原因是因为它无法完成握手:https://hpbn.co/websocket/#http-upgrade-negotiation