Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
websocket已成功握手,但未正确发送接收消息(C#服务器)_C#_.net_Html_Google Chrome_Websocket - Fatal编程技术网

websocket已成功握手,但未正确发送接收消息(C#服务器)

websocket已成功握手,但未正确发送接收消息(C#服务器),c#,.net,html,google-chrome,websocket,C#,.net,Html,Google Chrome,Websocket,打了一上午的架后,我得到了工作上的握手,但现在我被困在了发送和接收信息的过程中。我一直在寻找答案,但毫无结果,所以我想我最终会站到这里问:/ 到目前为止,我的客户非常简单: function testWebSocket() { if (!window.WebSocket) { alert('WebSockets are NOT supported by your browser.'); return; } try { va

打了一上午的架后,我得到了工作上的握手,但现在我被困在了发送和接收信息的过程中。我一直在寻找答案,但毫无结果,所以我想我最终会站到这里问:/

到目前为止,我的客户非常简单:

function testWebSocket() {
    if (!window.WebSocket) {
        alert('WebSockets are NOT supported by your browser.');
        return;
    }

    try {
        var ws = new WebSocket('ws://localhost:8181/websession');
        ws.onopen = function () {
            alert('Handshake successfully established. Ready for data...');
        };

        ws.onmessage = function (e) {
            alert('Got WebSockets message: ' + e.data);
        }

        ws.onclose = function () {
            alert('Connection closed.');
        };
    }
    catch (e) {
        alert(e);
    }
}
是的,我已经为此借用了很多代码……我只是想通过一个简单的“聊天应用程序”获得概念证明

我的服务器主要由两个类组成,SocketServer.cs和SocketClient.cs

它们如下:

SocketServer.cs
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用System.Net.Sockets;
Net系统;
使用System.IO;
命名空间WebSocketServer.Entities
{
类SocketServer
{
公共静态表单1父表单;
tcplistenersocketserver;
public static List ClientList=new List();
公共SocketServer(Form1 pForm)
{
parentForm=pForm;
parentForm.ApplyText(“套接字类已启动\r\n”);
socketServer=newtcplistener(IPAddress.Any,8181);
//告诉控制台它已启动
parentForm.ApplyText(“套接字服务器已启动\r\n”);
//创建连续循环以侦听新连接
//启动侦听器
socketServer.Start();
while(true)
{
//检查是否有任何传入的挂起连接
//为新连接创建新套接字客户端
TcpClient socketConnection=socketServer.AcceptTcpClient();
DateTime now=DateTime.now;
//向控制台写入消息以指示新连接
parentForm.ApplyText(“新连接的客户端-”+now.ToString(“MM/dd/yyyy h:MM:ss tt”)+“\r\n”);
//为此连接创建新的客户端对象
SocketClient SocketClient=新的SocketClient(socketConnection,父窗体);
}
}
公共静态void CloseClient(SocketClient whichClient)
{
ClientList.Remove(whichClient);
whichClient.Client.Close();
//处理客户端对象
whichClient.Dispose();
whichClient=null;
parentForm.ApplyText(“客户端已断开连接\r\n”);
}
公共静态void SendTextToClient(SocketClient sc,字符串文本)
{
StreamWriter writer=新的StreamWriter(sc.Client.GetStream());
//检查客户端是否仍然连接,然后发送文本字符串
尝试
{
如果(sc.Client.Connected)
{
writer.WriteLine(文本);
writer.Flush();
writer=null;
}
}
抓住
{
客户(sc);
}
}
公共静态无效发送广播(字符串文本)
{
流作者;
//循环遍历数组并向所有客户端发送文本
foreach(客户端列表中的SocketClient客户端)
{
if(client.client.Connected)
{
尝试
{
writer=newstreamwriter(client.client.GetStream());
writer.WriteLine(文本);
writer.Flush();
writer=null;
}
抓住
{
客户(客户);
}
}
}
}
}
}
SocketClient.cs
使用系统;
使用System.Collections.Generic;
使用系统文本;
使用System.Net.Sockets;
使用System.IO;
使用系统线程;
使用System.Security.Cryptography;
命名空间WebSocketServer.Entities
{
类SocketClient
{
公共TCP客户机;
流阅读器;
流作者;
表格1家长表格;
公共SocketClient(TcpClient客户端,Form1 pForm)
{
parentForm=pForm;
客户=客户;
线程clientThread=newthread(newthreadstart(StartClient));
clientThread.Start();
}
私有void StartClient()
{
SocketServer.ClientList.Add(这个);
//为此客户端创建读取器
reader=newstreamreader(Client.GetStream());
//为此客户端创建一个编写器
writer=newstreamwriter(Client.GetStream());
var headers=newdictionary();
字符串行=”;
而((line=reader.ReadLine())!=string.Empty)
{
如果(!string.IsNullOrEmpty(行))
{
var tokens=line.Split(新字符[]{':'},2);
如果(!string.IsNullOrWhiteSpace(line)&&tokens.Length>1)
{
headers[tokens[0]]=tokens[1].Trim();
}
}
}
字符串secWebSocketAccept=ComputeWebSocketAshakeSecurityHash09(头文件[“secWebSocketKey”]);
//仅向此客户端发送握手
WriteLine(“HTTP/1.1 101 Web套接字协议握手”);
WriteLine(“升级:WebSocket”);
writer.WriteLine(“连接:升级”);
writer.WriteLine(“WebSocket来源:http://localhost:63422/");
WriteLine(“WebSocket位置:ws://localhost:8181/websession”);
WriteLine(“SecWebSocket接受:+SecWebSocket接受”);
writer.WriteLine(“”);
writer.Flush();
SendBroadcast(“新客户端已连接”);
线程clientRun=新线程(新线程开始(RunClient));
clientRun.Start();
}
公共静态字符串ComputeWebSocketHand
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.IO;

namespace WebSocketServer.Entities
{
    class SocketServer
    {
        public static Form1 parentForm;
        TcpListener socketServer;
        public static List<SocketClient> ClientList = new List<SocketClient>();


        public SocketServer(Form1 pForm)
        {

            parentForm = pForm;
            parentForm.ApplyText("Socket Class Initiated\r\n");
            socketServer = new TcpListener(IPAddress.Any, 8181);
            // tell the console that it's started
            parentForm.ApplyText("Socket Server Started\r\n");

            // create continuous loops to listen for new connections
            // start the listener
            socketServer.Start();
            while (true)
            {
                // check for any incoming pending connections
                // create new socket client for new connection
                TcpClient socketConnection = socketServer.AcceptTcpClient();
                DateTime now = DateTime.Now;
                //write message to console to indicate new connection
                parentForm.ApplyText("New Client Connected - " + now.ToString("MM/dd/yyyy h:mm:ss tt") + "\r\n");
                // create new client object for this connection
                SocketClient socketClient = new SocketClient(socketConnection, parentForm);
            }
        }

        public static void CloseClient(SocketClient whichClient)
        {
            ClientList.Remove(whichClient);
            whichClient.Client.Close();
            // dispose of the client object
            whichClient.Dispose();
            whichClient = null;
            parentForm.ApplyText("Client Disconnected\r\n");
        }



        public static void SendTextToClient(SocketClient sc, string text)
        {
            StreamWriter writer = new StreamWriter(sc.Client.GetStream());
            // check if client is still connected, then send the text string
            try
            {
                if (sc.Client.Connected)
                {
                    writer.WriteLine(text);
                    writer.Flush();
                    writer = null;
                }
            }
            catch
            {
                CloseClient(sc);
            }

        }


        public static void SendBroadcast(string text)
        {
            StreamWriter writer;
            // loop through the array and send text to all clients
            foreach (SocketClient client in ClientList)
            {
                if (client.Client.Connected)
                {
                    try
                    {
                        writer = new StreamWriter(client.Client.GetStream());
                        writer.WriteLine(text);
                        writer.Flush();
                        writer = null;

                    }
                    catch
                    {
                        CloseClient(client);
                    }
                }
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.Text;
using System.Net.Sockets;
using System.IO;
using System.Threading;
using System.Security.Cryptography;

namespace WebSocketServer.Entities
{
    class SocketClient
    {
        public TcpClient Client;
        StreamReader reader;
        StreamWriter writer;
        Form1 parentForm;


        public SocketClient(TcpClient client, Form1 pForm)
        {
            parentForm = pForm;
            Client = client;
            Thread clientThread = new Thread(new ThreadStart(StartClient));
            clientThread.Start();
        }


        private void StartClient()
        {
            SocketServer.ClientList.Add(this);
            // create a reader for this client
            reader = new StreamReader(Client.GetStream());
            // create a writer for this client
            writer = new StreamWriter(Client.GetStream());

            var headers = new Dictionary<string, string>();

            string line = "";
            while ((line = reader.ReadLine()) != string.Empty)
            {
                if (!string.IsNullOrEmpty(line))
                {
                    var tokens = line.Split(new char[] { ':' }, 2);
                    if (!string.IsNullOrWhiteSpace(line) && tokens.Length > 1)
                    {
                        headers[tokens[0]] = tokens[1].Trim();
                    }
                }
            }


            String secWebSocketAccept = ComputeWebSocketHandshakeSecurityHash09(headers["Sec-WebSocket-Key"]);

            // send handshake to this client only
            writer.WriteLine("HTTP/1.1 101 Web Socket Protocol Handshake");
            writer.WriteLine("Upgrade: WebSocket");
            writer.WriteLine("Connection: Upgrade");
            writer.WriteLine("WebSocket-Origin: http://localhost:63422/");
            writer.WriteLine("WebSocket-Location: ws://localhost:8181/websession");
            writer.WriteLine("Sec-WebSocket-Accept: " + secWebSocketAccept);
            writer.WriteLine("");
            writer.Flush();

            SocketServer.SendBroadcast("New Client Connected");

            Thread clientRun = new Thread(new ThreadStart(RunClient));
            clientRun.Start();
        }

        public static String ComputeWebSocketHandshakeSecurityHash09(String secWebSocketKey)
         {
             const String MagicKEY = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
             String secWebSocketAccept = String.Empty;

             // 1. Combine the request Sec-WebSocket-Key with magic key.
             String ret = secWebSocketKey + MagicKEY;

             // 2. Compute the SHA1 hash
             SHA1 sha = new SHA1CryptoServiceProvider(); 
             byte[] sha1Hash = sha.ComputeHash(Encoding.UTF8.GetBytes(ret));

             // 3. Base64 encode the hash
             secWebSocketAccept = Convert.ToBase64String(sha1Hash);

             return secWebSocketAccept;
         }


        private void RunClient()
        {
            try
            {
                string line = "";
                while (true)
                {
                    line = reader.ReadLine();
                    if (!string.IsNullOrEmpty(line))
                    {
                        parentForm.ApplyText(line + "\r\n");
                        SocketServer.SendBroadcast(line);
                    }
                }
            }
            catch
            {
                parentForm.ApplyText("Client Disconnected\r\n");
                SocketServer.CloseClient(this);
            }
        }

        public void Dispose()
        {
            System.GC.SuppressFinalize(this);
        }
    }

}
public static void SendBroadcast(string text)
{
    StreamWriter writer;
    // loop through the array and send text to all clients
    foreach (SocketClient client in ClientList)
    {
        if (client.Client.Connected)
        {
            try
            {
                NetworkStream l_Stream = client.Client.GetStream();  
                List<byte> lb = new List<byte>();
                lb.Add(0x81);
                lb.Add(0x04);
                lb.AddRange(Encoding.UTF8.GetBytes("test"));
                l_Stream.Write(lb.ToArray(), 0, 6);
            }
            catch
            {
                CloseClient(client);
            }
        }
    }
}
            lb = new List<byte>();
            lb.Add(0x81);
            size = message.Length;//get the message's size
            lb.Add((byte)size); //get the size in bytes
            lb.AddRange(Encoding.UTF8.GetBytes(message));
            stream.Write(lb.ToArray(), 0, size+2); //I do size+2 because we have 2 bytes plus 0x81 and (byte)size