Original: C # (Superwebsocket) communicates with WebSocket
Client code
Click to see some introduction to WebSocket
1 <!DOCTYPE HTML>2 <HTML>3 <HeadLang= "en">4 <MetaCharSet= "UTF-8">5 <title></title>6 </Head>7 <Body>8 <inputtype= "button"ID= "Send"onclick= "Send ()"value= "Send">9 <inputtype= "text"ID= "message">Ten <Scripttype= "Text/javascript"> One varwsclient=NewWebSocket ('ws://localhost:40001'); A Wsclient.open=function(e) { - Console.log ("connected!"); - } the Wsclient.onclose=function(e) { - Console.log ("disconnected!"); - } - Wsclient.onmessage=function(e) { + Console.log ("Receive message:"+e.data); - } + Wsclient.onerror=function(e) { A Console.log (e.data); at } - functionSend () { - varOtext=document.getElementById ("message"); - wsclient.send (otext.value); - } - </Script> in </Body> - </HTML>Server-side code
Superwebsocket inherits the socket framework SuperSocket, which is a network implementation of a WebSocket server .
1 class Program2 {3 Static voidMain (string[] args)4 {5Websocketserver Server =Newwebsocketserver ();6Server. newsessionconnected + =server_newsessionconnected;7 8Server. Newmessagereceived + =server_newmessagereceived;9Server. sessionclosed + =server_sessionclosed;Ten Try One { AServer. Setup ("127.0.0.1",40001);//Setting up Ports -Server. Start ();//Turn on monitoring - } the Catch(Exception ex) - { - Console.WriteLine (ex. Message); - } + Console.readkey (); - } + A Static voidServer_sessionclosed (websocketsession session, SuperSocket.SocketBase.CloseReason value) at { - Console.WriteLine (session. Origin); - } - - Static voidServer_newmessagereceived (websocketsession session,stringvalue) - { in Console.WriteLine (value); - session. Send (value); to } + - Static voidServer_newsessionconnected (websocketsession session) the { * Console.WriteLine (session. Origin); $ }Panax Notoginseng}
At first I also tried to write a websocket server, but feel trouble, later or directly with Superwebsocket, because it is really simple and practical tall on. Can be installed directly in the NuGet package,
Incidentally, the common log4net and Njson have been installed, one step ah.
C # (Superwebsocket) communicates with WebSocket