C # implements the service-side WebSocket

Source: Internet
Author: User

At this stage of the socket communication using TCP, UDP protocol, where the TCP protocol is relatively safe and stable! This article is also to explain the main TCP (with the following in the study of not fine).

The following is a personal understanding of TCP/IP to communicate between three times handshake!

1. The client sends the paper to the server first

2. Reply after receiving the message from the server

3. Once the client receives the reply, it sends the confirmation message again. This is the time to formally connect.

First say the connection form:

Server monitoring: After the server opens the service, it enters the listening client connection status. At this time is not the specified listener that the client is in a waiting state (not paused, has been in real-time network monitoring), waiting for the client to find him to connect.

Client Connection: The client initiates a link request to the target server, and the originating request must know the IP and the corresponding port number.

Confirm Link: This time the service side of the listener is working, the client's request will respond to the client request, create a socket link. It is important to note that the link is not one-to-one, and the server will re-create a new socket service for the requesting client. So the server is still in listening state can still listen.

Well above is some basic introduction, mainly for a bit of things to do bedding, after all, to achieve the need to have a socket base, to go. Let's start with our complete websocket exercise! (There are some websocket that are implemented using plugins or class libraries online.) But what we're talking about is socket-based)

Not much else first create the socket server:

1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 usingSystem.Net.Sockets;7 usingSystem.Net;8 usingSystem.Threading;9 usingSystem.Text.RegularExpressions;Ten usingSystem.Security.Cryptography; One  A namespaceSocketservice - { -     classSocketservice the     { -         Private Static byte[] result =New byte[1024x768]; -         Private Static intMyprot =8885;//Port -         StaticSocket ServerSocket;//Server Services +          Public voidStart () -         { +             //Server IP Address AIPAddress IP = ipaddress.parse ("127.0.0.1"); at             //socket constructor for service registration -ServerSocket =Newsockets (AddressFamily.InterNetwork, SocketType.Stream, protocoltype.tcp); -             //bind IP Address: Port -Serversocket.bind (Newipendpoint (IP, Myprot)); -             //set a maximum of 10 queued connection requests -Serversocket.listen (Ten); inConsole.WriteLine ("boot Listener {0} succeeded", serverSocket.LocalEndPoint.ToString ()); -             //sending data via Clientsoket toThread MyThread =NewThread (listenclientconnect); + Mythread.start (); - console.readline (); the         } *         /// <summary>   $         ///Listening for client connectionsPanax Notoginseng         /// </summary>   -         Private  voidListenclientconnect () the         { +              while(true) A             { theSocket Clientsocket =serversocket.accept (); +                //Clientsocket.send (Encoding.ASCII.GetBytes ("Server Say Hello")); -Thread Receivethread =NewThread (ReceiveMessage); $ Receivethread.start (clientsocket); $             } -         } -  the         /// <summary>   -         ///Receiving MessagesWuyi         /// </summary>   the         /// <param name= "Clientsocket" ></param>   -         Private  voidReceiveMessage (Objectclientsocket) Wu         { -Socket Myclientsocket =(Socket) clientsocket; About              while(true) $             { -                 Try -                 { -                     //receiving data via Clientsocket A                     intReceivenumber =myclientsocket.receive (result); +                     //WebSocket When a connection is established, in addition to the three handshake of the TCP connection, the client and server in the WebSocket protocol need an additional handshake action to establish a connection the                     stringmsg = Encoding.UTF8.GetString (result,0, receivenumber); -                     varBuffer =result; $                     if(Msg. Contains ("Sec-websocket-key")) the                     { the  the myclientsocket.send (packagehandshakedata (buffer, receivenumber)); the  -                        //return; in                     } the                     varSS =analyzeclientdata (result, receivenumber); theConsole.WriteLine ("receive client {0} message {1}", MyClientSocket.RemoteEndPoint.ToString (), Encoding.UTF8.GetString (result,0, Receivenumber)); About                 } the                 Catch(Exception ex) the                 { the Console.WriteLine (ex. Message); + Myclientsocket.shutdown (socketshutdown.both); - myclientsocket.close (); the                      Break;Bayi                 } the             } the         } -  } -}
View Code

Code comment I've written it in detail! I hope you can read it (haha)!

See here some smart netizens may find the problem! or the operation but did not succeed also see the difference. There is no mistake, here I would like to point out that some websocket is a bit different from the socket is that the first message of his handshake and return information is required in a specific format.

The so-called Response header field requires special handling. In not doing the corresponding response processing browser will be reported "handshake unsuccessful" Error!

Reference URL: http://www.cnblogs.com/smark/archive/2012/11/26/2789812.html

If the initial classmate does not understand please move to another blog, detailed encapsulation of this method to resolve this error. (Convenient for some students to find the wrong solution, because I was also engaged in a morning to find this problem, but also hope Haihan)

Finally we just need to invoke the service in the Main method

At this point the service-side code is accomplished! Below we use JS to make the request is possible.

The following HTML suggestion code can also go to see the tutorial:

HTML code:

    <Body>        <ahref= "Javascript:websockettest ()">Run WebSocket</a>        <ahref= "Javascript:websocketclose ()">Close WebSocket</a>        <DivID= "Look"class= "M">        </Div>        <inputID= "message">        <ahref= "Javascript:send ()">Send Message</a>    </Body>

JavaScript code:

varws;functionwebsockettest () {if("WebSocket"inchwindow) {Alert ("Your browser supports websocket!"); //open a Web socketWS =NewWebSocket ("ws://127.0.0.1:8885"); Ws.onopen=function() {            //The Web Socket is connected, sending data using the Send () methodWs.send ("Send Data"); Alert ("Data Sent ...");        }; Ws.onmessage=function(evt) {varReceived_msg =Evt.data; document.getElementById ("Look"). html+=received_msg; Alert ("Data Received ...");        }; Ws.onclose=function() {            //Close WebSocketAlert ("Connection closed ...");    }; } Else {        //Browser does not support WebSocketAlert ("Your browser does not support websocket!"); }}functionWebsocketclose () {ws.close (); Alert ("Communication closed.")}functionSend () {varmsg= document.getElementById ("message"). Value; if(msg== "" | | msg==undefined) {Alert ("Please fill in the Send content!" ")        return; } ws.send ("1111111111"); Alert ("Sent a message")}
View Code

Finally attached run:

C # implements the service-side WebSocket

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.