Step by step to build webim (4) -- Special Features of comet

Source: Internet
Author: User
Yunxiang online chat rooms provide online chat rooms, webim, online storage, and other services. webim can create groups (unlimited number of users) for free and store chat records online.

Webim Series

We have already used comet to implement a simple webim in step-by-step webim (1). What is the difference between Comet and general web pages, this article describes the differences between the two by writing a simple HTTP server.

The so-called website can be understood as an application on the server.ProgramThe application creates a socket and listens on port 80 (usually port 80), and accepts and processes HTTP requests sent by the browser.

When you open a webpage, the browser will send an HTTP request to the server, and then the browser will remain waiting to know that the server has sent an HTTP response. When the server receives this HTTP request, it will parse the HTTP request header and send data (web pages, images, data, etc.) to the browser based on the information in the message ), after the server sends the data, the browser stops waiting and displays the webpage. For more information about the interaction between the browser and the server, read this blog:

Differences between HTTP protocol and post and get Operations & How to Use post and get in C #

Based on the interaction process described above, you can write a simple HTTP server that listens on port 8000 and only provides two webpages.

Http: // localhost: 8000/index.htm

Http: // localhost: 8000/comet.htm

In other words, the link is suspended first and a thread is started. The new thread will wait 5 seconds before sending the webpage. ServerSource codeAs follows:

 Using System;  Using  System. Collections. Generic;  Using  System. text;  Using  System. IO;  Using  System. Text. regularexpressions;  Using  System. net;  Using  System. net. Sockets;  Using  System. Threading;  Namespace  HTTP {  Class  Program  { Static  String  Responeformat =  "HTTP/1.1 200 OK \ r \ n"  +  "Content-Length: {0} \ r \ n"  +  "Connection: Close \ r \ n"  +  "Content-Type: text/html \ r \ n"  +  "\ R \ n"  +  "{1} \ r \ n"  ;  Static void  Main (  String  [] ARGs ){ Socket  Server =  New  Socket  (  Addressfamily  . InterNetwork,  Sockettype  . Stream,  Protocoltype  . TCP );  // Listen to port 8000  Endpoint  Ep =  New  Ipendpoint  (  New  IPaddress  ( New byte  [] {127, 0, 0, 1}), 8000); server. BIND (EP); server. Listen (5 );  While  (  True  ){  Socket  Client = server. Accept ();  // Read the HTTP packet header  String  Header =  String  . Empty;  While  (Header. indexof (  "\ R \ n"  ) <0 ){ Byte  [] Buffer =  New byte  [1024];  Int  Len = client. Receive (buffer); header + =  Encoding  . ASCII. getstring (buffer, 0, Len );}  Console  . Writeline (  "============================================== ========================================================== ="  );  Console  . Write (header );  RegEx  Reg = New  RegEx  (  @ "Get \ s + ([^ \ s \ r \ n] +) \ s + HTTP/1.1 \ s * \ r \ n"  ,  Regexoptions  . Ignorecase );  Match  Match = reg. Match (header );  If  (Match. Success ){  String  Fname =  Path  . Getfilename (match. Groups [1]. Value). tolower ();  If  (Fname = "Index.htm"  ){  String  Html =  String  . Format (  "<Span style = 'color: red; fonst-size: 24px; '> {0} </span>"  ,  Datetime  . Now );  String  Response =  String  . Format (responeformat, HTML. length, HTML );  // Send an HTTP response. After this HTTP request is completed, the browser will immediately accept the webpage  Client. Send ( Encoding  . Utf8.getbytes (response); client. Close ();}  Else if  (Fname =  "Comet.htm"  ){  // If the data is not ready at this time, the link will be suspended first, and the webpage will be sent to the browser in another thread. // the browser will wait until the thread does not send an HTTP response, wait until the starting thread sends a response  Thread  Thread =  New  Thread  (  New  Parameterizedthreadstart (Sendthreadentry); thread. Start (client );}  Else  {Client. Close ();}}}}  Static void  Sendthreadentry (  Object  Data ){  // Wait 5 S  Thread  . Sleep (5000 );  Socket  Client = Data  As  Socket  ; String  Html =  String  . Format (  "<Span style = 'color: red; fonst-size: 24px; '> {0} </span>"  ,  Datetime  . Now );  String  Response =  String  . Format (responeformat, HTML. length, HTML );  Console  . Writeline (  "Send Response"  );  // Send an HTTP response. After the HTTP request ends, the browser receives the webpage. Before that, the browser waits. Client. Send (  Encoding  . Utf8.getbytes (response); client. Close ();}}} 

Of course, the data sent to comet.htm may not start a new thread. You can save the client (for example, save it to a global variable) and call the client's send method to send the data after the data is ready.

Source code download

If this article is helpful to you, you can click here to recommend

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.