supersocket例子 c#的Websocket server和web client

supersocket例子,实现c#的Websocket server和web client之间通信,ithub的supersocket地址 star大约2000,用着还算方便,推荐一下。supersocket还支持企业级,GitHub上的例子里面有在线聊天的例子。

supersocket是c#写的,他的官网是:supersocket

Github的地址 star大约2000,用着还算方便,推荐一下

c#的server端源码:(复制能用)

using SuperSocket.SocketBase;
using SuperSocket.WebSocket;
using System;
using System.Linq;

namespace lswebsocket
{
    public class SuperSocketServerG
    {
        private static WebSocketServer appServer = new WebSocketServer();

        public void InitServer(int port)
        {
            //Setup the appServer
            if (!appServer.Setup(port)) //Setup with listening port
            {
                Console.WriteLine("Failed to setup!");
                Console.ReadKey();
                return;
            }

            appServer.NewSessionConnected += appServer_NewSessionConnected;
            appServer.SessionClosed += appServer_NewSessionClosed;
            appServer.NewDataReceived += AppServer_NewDataReceived;
            appServer.NewMessageReceived += appServer_NewMessageReceived;
        }

        public void StartServer()
        {
            //Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }
        }

        public void StopServer()
        {
            //Stop the appServer
            appServer.Stop();
        }


        static void appServer_NewSessionConnected(WebSocketSession session)
        {
            Console.WriteLine($"故障设置有人进入");

            var count = appServer.GetAllSessions().Count();
            Console.WriteLine("~~" + count);
            //            session.Send("Welcome to SuperSocket Telnet Server");
        }

        static void appServer_NewSessionClosed(WebSocketSession session, CloseReason aaa)
        {
            Console.WriteLine($"故障设置有人离开" + session.SessionID + aaa.ToString());
            var count = appServer.GetAllSessions().Count();
            Console.WriteLine(count);
        }

        private void AppServer_NewDataReceived(WebSocketSession session, byte[] value)
        {

        }

        static void appServer_NewMessageReceived(WebSocketSession session, string message)
        {

        }
    }
}

HTML+js的client(下面的仅供参考,)

<!DOCTYPE html>
<html lang="cn">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>联锁大厅</title>
    <link rel="stylesheet" type="text/css" href="__PUBLIC__/css/style.css" />
    <script type="text/javascript" src="__PUBLIC__/js/jquery-1.7.1.min.js"></script>
    <script type="text/javascript" src="__PUBLIC__/js/jquery-ui-1.8.18.custom.min.js"></script>
    <script type="text/javascript" src="__PUBLIC__/js/function.js"></script>
    <script>
        function doPost(to, p) {  // to:提交动作(action),p:参数
            var myForm = document.createElement("form");
            myForm.method = "post";
            myForm.action = to;
            for (var i in p){
                var myInput = document.createElement("input");
                myInput.setAttribute("name", i);  // 为input对象设置name
                myInput.setAttribute("value", p[i]);  // 为input对象设置value
                myForm.appendChild(myInput);
            }
            document.body.appendChild(myForm);
            myForm.submit();
            document.body.removeChild(myForm);  // 提交后移除创建的form
        }

        /*                
        * *功能: JS跳转页面,并已POST方式提交数据       
        * 参数: URL 跳转地址 PARAMTERS 参数       
        * 返回值:       
        * 创建时间:20160713        *
        * 创建人:       
        * */        
        function openxyj() {
            var parames = new Array();
            parames.push({ name: "userid", value: "{$userid}"});
            parames.push({ name: "activeid", value: "{$activeid}"});
            Post("{:url('index/index/xyj')}","_blank" ,parames);
            return false;
        }

        function opengzsz() {
            var parames = new Array();
            parames.push({ name: "userid", value: "{$userid}"});
            parames.push({ name: "activeid", value: "{$activeid}"});
            Post("{:url('index/index/gzsz')}","_self" ,parames);
            return false;
        }
    </script>
    <SCRIPT LANGUAGE="JavaScript">
        var host = "ws:192.168.1.51:2011";
        socket = new WebSocket(host);
        var uid = "{$userid}";
        var aid = "{$activeid}";

        function opennew(index) {
            var r = confirm("确认进入实验吗?点击确定,你将会打开故障设置页面和学员机页面。")
            if (r == true) {
                socket.send("{$userid}"+'|'+index);
                openxyj();
                opengzsz();
            } else {

            }
        }

        var userid_group = "userid|"+"{$userid}";
        $(document).ready(function()
        {
            // 建立连接
            if(userid_group=="")
            {
                alert("错误:"+userid_group+"为空");
                return;
            }
            connect();
        });

        // 连接函数
        function connect() {
            try {
                // alert('Socket Status:'+socket.readyState);
                socket.onopen = function () {
                    // alert('Socket Status:'+socket.readyState+' (open) ');
                    // var pseudoName = userid_group;
                    // socket.send('0'+pseudoName);
                    // socket.send('3subscribe');
                    // socket.send(userid_group);
                }

                socket.onmessage = function (msg) {
                    str = msg.data;
                    console.log(str);
                    var clientstate = str.split("");
                    for (var i = 0;i < clientstate.length;i++){
                        if(clientstate[i] == 0)
                        {
                            // 空闲
                            // console.log($('#room_icon_'.$i));
                            // $('#room_icon_'.$i).attr()
                            var room_icon = "";
                            room_icon =  'room_icon_'+i;
                            document.getElementById(room_icon).style.display ="none";
                            var index = i+1;
                            document.getElementById('room_no_'+i).innerHTML = '<a href="javascript:opennew('+i+');">'+index+'</a>';
                        }
                        else {
                            // 占用
                            var room_icon = "";
                            room_icon =  'room_icon_'+i;
                            document.getElementById(room_icon).style.display = "flex";
                            var index = i+1;
                            document.getElementById('room_no_'+i).innerHTML = '<h4 class="feature-title h3-mobile">'+index+'(占)</h4>';
                        }
                    }
                }
                socket.onclose = function () {
                    // alert('Socket Status:'+socket.readyState+' (close)');
                }
            }
            catch (exception) {
                alert('Error '+ exception);
            }
        }
    </script>
</head>
<body>
<div class="wrapper_zhuji" id ="wrapper_zhuji">
    <?php for ($i=0;$i<300;$i+=1){
    echo '
    <div class="box_zj">
        <div class="feature is-revealing" style="visibility: visible;">
            <div class="feature-inner">
                <div class="feature-icon" id="room_icon_'.$i.'" style="display: none;">
                    <img src="__PUBLIC__/image/bzz.png" style="width: 150px;height: 75px;">
                </div>
                <div id="room_no_'.$i.'">
                    <a href="javascript:opennew(\''.$i.'\');">'.($i+1).'</a>
                </div>
            </div>
        </div>
    </div>';}?>
</div>
</body>
</html>

本站原创,未经允许不得转载:lingkb » supersocket例子 c#的Websocket server和web client
赞(0)

评论抢沙发