标题:c#websocket服务器,已实现单客户访问,求多客户端得连接方法
只看楼主
xzwtsdjd
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2011-6-2
 问题点数:0 回复次数:1 
c#websocket服务器,已实现单客户访问,求多客户端得连接方法
因为单客户端连接已经实现,但是没有意义,既然是服务器就需要多客户端同时访问,所以我想通过多线程的方法实现,但是无奈c#刚开始学习,虽然查看了大量资料,还是不知道怎么改,大家帮帮忙啊
源码如下:控制台程序

using System;   
using System.Collections.Generic;   
using System.Text;   
using    
using    
using System.Security.Cryptography;   
using System.Web.Security;   
using    
namespace Room   
{   
    class Program   
    {   
        static void Main(string[] args)   
        {   
            Console.WriteLine("服务器启动中...");   
            IPEndPoint ipe = new IPEndPoint(IPAddress.Parse("192.168.1.80"), 2000);   
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);   
            socket.Bind(ipe);   
            socket.Listen(60);   
            Console.WriteLine("服务器启动完毕...");   
            bool isfirst = true;   
            bool run = true;   
            try  
            {   
                Socket a = socket.Accept();   
                while (run)   
                {   
                    byte[] bytes = new byte[1024];   
                    int bytelength = a.Receive(bytes);   
                    Console.WriteLine("接收完毕。");  
                    #region websocket握手   
                    if (isfirst)   
                    {   
                        string recStr = Encoding.UTF8.GetString(bytes, 0, bytelength);   
                        string[] ss = recStr.Split(Environment.NewLine.ToCharArray());   
                        string k1 = ss[10].Substring(20);   
                        string k2 = ss[12].Substring(20);   
                        byte[] last = new byte[8];   
                        for (int i = 0; i < 8; i++)   
                        {   
                            last[i] = bytes[bytelength - 8 + i];   
                        }   
                        uint key1 = (uint)(long.Parse(FilterNonNumber(k1)) / FilterNonEmpty(k1).Length);   
                        uint key2 = (uint)(long.Parse(FilterNonNumber(k2)) / FilterNonEmpty(k2).Length);   
                        byte[] byteTemp1 = BitConverter.GetBytes(key1);   
                        byte[] byteKey1 = new byte[4];   
                        byte[] byteTemp2 = BitConverter.GetBytes(key2);   
                        byte[] byteKey2 = new byte[4];   
                        for (int i = 0; i < 4; i++)   
                        {   
                            byteKey1[i] = byteTemp1[3 - i];   
                            byteKey2[i] = byteTemp2[3 - i];   
                        }   
                        MemoryStream ms = new MemoryStream();   
                        ms.Write(byteKey1, 0, 4);   
                        ms.Write(byteKey2, 0, 4);   
                        ms.Write(last, 0, 8);   
                        ms.Flush();   
                        byte[] byteMs = ms.ToArray();   
                        ms.Dispose();   
                        MD5 md5 = MD5.Create();   
                        byte[] md = (byteMs);   
                        MemoryStream ms1 = new MemoryStream();   
                        string sendStr = "HTTP/1.1 101 WebSocket Protocol Handshake\r\nUpgrade: WebSocket\r\nConnection: Upgrade\r\nSec-WebSocket-Origin: null\r\nSec-WebSocket-Location: ws://192.168.1.80:2000/\r\n\r\n";   
                        byte[] temp = Encoding.UTF8.GetBytes(sendStr);   
                        ms1.Write(temp, 0, temp.Length);   
                        ms1.Write(md, 0, md.Length);   
                        ms1.Flush();   
                        byte[] byteSend = ms1.ToArray();   
                        ms1.Dispose();   
                        a.Send(byteSend, byteSend.Length, 0);   
                        Console.WriteLine("发送完毕。");   
                        isfirst = false;   
                    }  
                    #endregion   
                    else  
                    {   
                        if (bytelength > 2)   
                        {   
                            string recStr = Encoding.UTF8.GetString(bytes, 1, bytelength - 2);   
                            MemoryStream ms2 = new MemoryStream();   
                            string strSend = "发送回去的是中文。";   
                            byte[] byteSend = Encoding.UTF8.GetBytes(strSend);   
                            ms2.WriteByte(0);   
                            ms2.Write(byteSend, 0, byteSend.Length);   
                            ms2.WriteByte(255);   
                            ms2.Flush();   
                            a.Send(ms2.ToArray());   
                            ms2.Dispose();   
                            if (recStr.Equals("exit"))   
                            {   
                                run = false;   
                                Console.WriteLine("用户已退出。");   
                            }   
                            else  
                            {   
                                Console.WriteLine("接收到:" + recStr);   
                            }   
                        }   
                        else  
                        {   
                            run = false;   
                            Console.WriteLine("用户已退出。");   
                        }   
                    }   
                }   
                Console.ReadLine();   
                a.Close();   
                socket.Close();   
            }   
            catch (Exception e)   
            {   
                Console.WriteLine(e.Message);   
            }   
            finally  
            {   
                socket.Close();   
            }   
        }   
        public static string FilterNonNumber(string str)   
        {   
            if (str == null)   
            {   
                return "";   
            }   
            char[] c = str.ToCharArray();   
            StringBuilder sb = new StringBuilder();   
            for (int i = 0, len = c.Length; i < len; i++)   
            {   
                if (char.IsNumber(c[i]))   
                {   
                    sb.Append(c[i]);   
                }   
            }   
            return sb.ToString();   
        }   
        public static string FilterNonEmpty(string str)   
        {   
            if (str == null)   
            {   
                return " ";   
            }   
            char[] c = str.ToCharArray();   
            StringBuilder sb = new StringBuilder();   
            for (int i = 0, len = c.Length; i < len; i++)   
            {   
                if (c[i] == ' ')   
                {   
                    sb.Append(c[i]);   
                }   
            }   
            if (sb.ToString().Length == 0)   
            {   
                return " ";   
            }   
            else  
            {   
                return sb.ToString();   
            }   
        }   
    }   
}  

测试用的html页面
<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
<title>1</title>  
<mce:script type="text/javascript"><!--   
if (!window.WebSocket) {   
    alert("WebSocket not supported by this browser!");   
}   
var ws;   
function display() {   
    if(ws == null){   
        ws = new WebSocket("ws://192.168.1.80:2000");   
        ws.onmessage = function(evt) {   
            alert("接收到信息:"+evt.data);   
        };   
           
        ws.onclose = function() {   
            alert("连接已关闭。");   
            ws = null;   
        };   
           
        ws.onerror = function(evt){   
            alert("连接出错:"+evt.data);   
            ws = null;   
        }   
           
        ws.onopen = function(evt) {   
            alert("连接已打开。");   
        };   
    }   
}   
function wssend(){   
    if(ws!=null){   
        var sendstr = document.getElementById("txtSend").value;   
        if(sendstr == ""){   
            sendstr = " ";   
        }   
        ws.send(sendstr);   
    }else{   
        alert("连接失效。");   
    }   
}   
// --></mce:script>  
</head>  
<body style="text-align:center;" mce_style="text-align:center;">  
<input type="button" value="点我" onclick="display()"/>  
<br />  
<input type="text" id="txtSend" /><input type="button" id="btnSend" value="发送" onclick="wssend()"/>  
</body>  
</html>  

如果要试用的话,记得改IP和端口
代码转载:http://blog.


搜索更多相关主题的帖子: 控制台 多线程 客户端 服务器 
2011-06-02 17:36
q114687576
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2016-3-31
得分:0 
http://www. 在线WebSocket测试,客户端完美兼容IE6及以上浏览器,服务端采用【C#.NET】异步socket开发,支持多客户同时在线,服务端发送数据长度不限。
2016-03-31 18:53



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-341730-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.111048 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved