要做个简单的实时通讯对话,
网上找到了SuperSocket 快速做服务端应用,下面自己写的简单服务端 class Program
    {        static List<AppSession> _sessions = new List<AppSession>();        static void Main(string[] args)
        {
            Console.WriteLine("Press any key to start the server!");
            Console.ReadKey();
            Console.WriteLine();            var appServer = new AppServer();            /*
                name: 服务器实例的名称;
                serverType: 服务器实例的类型的完整名称;
                serverTypeName: 所选用的服务器类型在 serverTypes 节点的名字,配置节点 serverTypes 用于定义所有可用的服务器类型,我们将在后面再做详细介绍;
                ip: 服务器监听的ip地址。你可以设置具体的地址,也可以设置为下面的值 Any - 所有的IPv4地址 IPv6Any - 所有的IPv6地址
                port: 服务器监听的端口;
                listenBacklog: 监听队列的大小;
                mode: Socket服务器运行的模式, Tcp (默认) 或者 Udp;
                disabled: 服务器实例是否禁用了;
                startupOrder: 服务器实例启动顺序, bootstrap 将按照此值的顺序来启动多个服务器实例;
                sendTimeOut: 发送数据超时时间;
                sendingQueueSize: 发送队列最大长度, 默认值为5;
                maxConnectionNumber: 可允许连接的最大连接数;
                receiveBufferSize: 接收缓冲区大小;
                sendBufferSize: 发送缓冲区大小;
                syncSend: 是否启用同步发送模式, 默认值: false;
                logCommand: 是否记录命令执行的记录;
                logBasicSessionActivity: 是否记录session的基本活动,如连接和断开;
                clearIdleSession: true 或 false, 是否定时清空空闲会话,默认值是 false;
                clearIdleSessionInterval: 清空空闲会话的时间间隔, 默认值是120, 单位为秒;
                idleSessionTimeOut: 会话空闲超时时间; 当此会话空闲时间超过此值,同时clearIdleSession被配置成true时,此会话将会被关闭; 默认值为300,单位为秒;
                security: Empty, Tls, Ssl3. Socket服务器所采用的传输层加密协议,默认值为空;
                maxRequestLength: 最大允许的请求长度,默认值为1024;
                textEncoding: 文本的默认编码,默认值是 ASCII;
                defaultCulture: 此服务器实例的默认 thread culture, 只在.Net 4.5中可用而且在隔离级别为 'None' 时无效;
                disableSessionSnapshot: 是否禁用会话快照, 默认值为 false.
                sessionSnapshotInterval: 会话快照时间间隔, 默认值是 5, 单位为秒;
                keepAliveTime: 网络连接正常情况下的keep alive数据的发送间隔, 默认值为 600, 单位为秒;
                keepAliveInterval: Keep alive失败之后, keep alive探测包的发送间隔,默认值为 60, 单位为秒;
             */
            var serverConfig = new ServerConfig
            {
                Port = 4141, //set the listening port
                Ip = "Any",
                Name = "XHS_Server",
                //Other configuration options
                Mode = SocketMode.Tcp,
                MaxConnectionNumber = 100,
                IdleSessionTimeOut = 600,
                TextEncoding = "UTF-8",
                SyncSend = true,
                SendBufferSize = 1024,
                ReceiveBufferSize = 1024,
                LogBasicSessionActivity = true,
                LogAllSocketException = true,
                KeepAliveTime = 300
            };
            serverConfig.SyncSend = true;
            
            //Setup the appServer
            if (!appServer.Setup(serverConfig))
            {
                Console.WriteLine("Failed to setup!");
                Console.ReadKey();
                return;
            }
            appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);
            appServer.NewRequestReceived += new RequestHandler<AppSession, StringRequestInfo>(appServer_NewRequestReceived);
            appServer.SessionClosed += new SessionHandler<AppSession, CloseReason>(appServer_SessionClosed);            Console.WriteLine();
            //Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }            Console.WriteLine("The server started successfully, press key 'q' to stop it!");            while (Console.ReadKey().KeyChar != 'q')
            {
                Console.WriteLine();
                continue;
            }            Console.WriteLine();
            //Stop the appServer
            appServer.Stop();            Console.WriteLine("The server was stopped!");        }        static void appServer_NewSessionConnected(AppSession session)
        {
            _sessions.Add(session);
            session.Send("Welcome to SuperSocket Telnet Server");
        }        static void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
        {
            string Key = requestInfo.Key;
            MyLogHelper.Instance.Debug("requestInfo.Key" + Key);
            Logger.Log(string.Format("{0}{1}", Key, requestInfo.Body));
            //session.Send(Key);            foreach(var s in _sessions)
            {
                s.Send(Key);
            }
        }        static void appServer_SessionClosed(AppSession session,CloseReason closereason)
        {
            Logger.Log("断开连接!");
            session.Close();
        }        //public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo)
        //{
        //    session.Send(requestInfo.Body);
        //}
    }
}用户windows命令直接telnet是可以链接上的,而且也可以发消息;但是用html5 的websocket就是连不上,提示:
WebSocket connection to 'ws://192.168.108.104:4141/' failed: Error during WebSocket handshake: Invalid status line
下面是我的html5代码:/// <reference path="~/js/jquery-1.9.1-vsdoc.js" />$(document).ready(function () {    var WebSocketsExist = true;
    try {
        //new WebSocket("ws://" + $("#Connection").val());
        var dummy = new WebSocket("ws://" + $("#Connection").val());
    } catch (ex) {
        try {
            webSocket = new MozWebSocket("ws://" + $("#Connection").val());
        }
        catch (ex) {
            WebSocketsExist = false;
        }
    }    if (WebSocketsExist) {
        Log("您的浏览器支持WebSocket. 您可以尝试连接到聊天服务器!");
        
    } else {
        Log("您的浏览器不支持WebSocket。请选择其他的浏览器再尝试连接服务器。");
        
    }
    
});var ws;
var SocketCreated = false;
function ConnectionSocket()
{
    Log("<li>准备连接在线交流服务器 ...</li>");    try{
        if ("WebSocket" in window) {
            ws = new WebSocket("ws://" + $("#Connection").val());
        }
        else if ("MozWebSocket" in window) {
            ws = new MozWebSocket("ws://" + $("#Connection").val());
        }
        SocketCreated = true;
    }
    catch (ex) {
        Log(ex);
        return;
    }    ws.onopen = WSonOpen;
    ws.onmessage = WSonMessage;
    ws.onclose = WSonClose;
    ws.onerror = WSonError;
}function connectjs() {
    ConnectionSocket();
}//发送连接消息
function WSonOpen() {
    Log("<li>连接已经建立。</li>");
    ws.send("login:" + $("#txtName").val());
};//写消息
function WSonMessage(event) {
    Log(event.data);
};//关闭
function WSonClose() {
    Log("<li>【" + $("#txtName").val() + "】离开了!</li>");
};//错误
function WSonError(evt) {
   
    console.log(evt);
    Log("<li>远程连接中断:" + evt + "</li>");
    SocketCreated = false;
  
};function sendjs()
{
    if ($("#talktxt").val().trim() != "") {
        ws.send("<li><span>" + $("#txtName").val() + " : </span>[" + Gettime() + "]<br/>" + $("#talktxt").val() + "</li>");
        $("#talktxt").val("");
    };}function Log(text)
{
    var st = "<li>" + text + "</li>";    $("#Ul_Talk").append(st);
    $("#Ul_Talk").scrollTop($("#Ul_Talk")[0].scrollHeight);
}function Gettime() {
    var myDate = new Date();
    var Minu = myDate.getMinutes();
    if (String(Minu).length != 2) {
        Minu = "0" + String(Minu);
    }
    var Second = myDate.getSeconds();
    if (String(Second).length != 2) {
        Second = "0" + String(Second);
    }    //myDate.getFullYear() + "/" + month + "/" + day + " " + 
    var todayInfo = myDate.getHours() + ":" + Minu + ":" + myDate.getSeconds();    return todayInfo;
}
请大家 帮看看 ,在这里先谢谢大家了~~

解决方案 »

  1.   

    服务端 用 WebSocketServer
      

  2.   

    websocket用过,使用的是局域网ip.
      

  3.   

    websocket不能直接连接一般的SOCKET服务器,因为websocket又封装了一层东西,直接连接一般的socket服务区 那边识别不了
      

  4.   

    连接的时候一直报错:
    WebSocket connection to 'ws://192.168.31.131:2012/' failed: Error during WebSocket handshake: Invalid status line
      

  5.   

    我这边也在做JS跟JAVA客户端交互 也出现了这样的问题0.0
      

  6.   


    是这样的。Socket 不是 WebSocket。你拿了一个低级的东西当高级服务了。如果你想自己开发 WebSocket server,你就要实现其通讯协议。而不是随便弄一个 Socket 程序。
      

  7.   

    要用websocket