2014-06-17 49 views
0

我嘗試使用websockets和Fleck庫創建簡單的聊天室。現在我可以向所有用戶發送消息。這裏是我的代碼:使用Fleck庫的WebSockets

FleckLog.Level = LogLevel.Info; 
     var allsockets = new List<IWebSocketConnection>(); 
     var server = new WebSocketServer("ws://localhost:8181"); 

     server.Start(socket => 
     { 
      socket.OnOpen =() => 
       { //See socket.ConnectionInfo.* for additional informations 
        Console.WriteLine(String.Empty); 
        Console.WriteLine("[NEW CLIENT CONNECTION]======================"); 
        Console.WriteLine("GUID: " + socket.ConnectionInfo.Id); 
        Console.WriteLine("IP: " + socket.ConnectionInfo.ClientIpAddress); 
        Console.WriteLine("Port: " + socket.ConnectionInfo.ClientPort); 
        Console.WriteLine("============================================="); 
        Console.WriteLine(String.Empty); 
        allsockets.Add(socket); 

       }; 

      socket.OnClose =() => 
      { 
        Console.WriteLine(String.Empty); 
        Console.WriteLine("[DISCONNECTED CLIENT]======================="); 
        Console.WriteLine("GUID: " + socket.ConnectionInfo.Id); 
        Console.WriteLine("IP: " + socket.ConnectionInfo.ClientIpAddress); 
        Console.WriteLine("Port: " + socket.ConnectionInfo.ClientPort); 
        Console.WriteLine("============================================="); 
        Console.WriteLine(String.Empty); 
        allsockets.Remove(socket); 
       }; 

      socket.OnMessage = (message) => 
      { 
       //TODO: Json.Net Deserialize 
       Console.WriteLine("[JSON MESSAGE] " + message); 
       allsockets.ToList().ForEach(s => s.Send(message)); 
      }; 
     }); 

客戶端代碼(Java腳本):

// Websocket Endpoint url 
var URL = 'ws://localhost:8181'; 

var chatClient = null; 

function connect() { 
    chatClient = new WebSocket(URL); 
    chatClient.onmessage = function (event) { 
     var messagesArea = document.getElementById("messages"); 
     var jsonObj = JSON.parse(event.data); 
     var message = "<"+ jsonObj.user + "> " + jsonObj.message + "\r\n"; 
     messagesArea.value = messagesArea.value + message; 
     messagesArea.scrollTop = messagesArea.scrollHeight; 
    }; 
} 

function disconnect() { 
    chatClient.close(); 
    } 

function sendMessage() { 
    var user = document.getElementById("userName").value.trim(); 
    if (user === "") 
     alert ("Please enter your name!"); 

    var inputElement = document.getElementById("messageInput"); 
    var message = inputElement.value.trim(); 
    if (message !== "") { 
     var jsonObj = {"user" : user, "message" : message}; 
     chatClient.send(JSON.stringify(jsonObj)); 
     inputElement.value = ""; 
    } 
    inputElement.focus(); 
} 

如何添加到該代碼的安全層WSS?

非常感謝!

回答