Advertisement
Guest User

Websocket

a guest
Nov 13th, 2018
613
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.37 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using WebSocketSharp;
  7. using WebSocketSharp.Server;
  8.  
  9. namespace Websocket_Server
  10. {
  11.     // Task I:  Modify this websocket behavior so that it remembers all messages.
  12.     //          Whenever there is a new client connected, send all stored messages to the client
  13.     //          so the client knows the history of the conversation.
  14.     // Task II: Add timestamp (just the hour and minute) to the messages
  15.     //          (see http://stackoverflow.com/questions/21219797/how-to-get-correct-timestamp-in-c-sharp
  16.     //           for an example on how to get a timestamp).
  17.     class Chat : WebSocketBehavior
  18.     {
  19.         static List<String> chatHistory = new List<string>();
  20.         protected override void OnOpen()
  21.         {
  22.             foreach (string msg in chatHistory)
  23.             {
  24.                 Sessions.SendTo(this.ID, msg);
  25.             }
  26.  
  27.         }
  28.  
  29.         protected override void OnMessage(MessageEventArgs e)
  30.         {
  31.             // Retrieve message from client
  32.  
  33.             string timeStamp = DateTime.Now.ToString("HHmm");
  34.  
  35.             string msg = e.Data;
  36.  
  37.             chatHistory.Add(timeStamp + ": " msg + "\n");
  38.  
  39.             // Broadcast message to all clients
  40.             Sessions.Broadcast(timeStamp + msg);
  41.         }
  42.     }
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement