Push technology to achieve the chat room

2008-08-20  来源:本站原创  分类:Web  人气:315 

Push-based chat rooms in China are now more common  .  The greatest feature of this chat room is to not use the browser to refresh every new way for some time  ,  And allow the server to the client from time to time to write the content of chat  .  When people speak  ,  Screen will appear the new chat  ,  And the chat content is constantly rolling up  ,  If the browser status bar in the words of  ,  Can see the progress bar is always in state of the download page  .  Even if such a chat room to accommodate hundreds of people  ,  Performance will not significantly reduce the  .  The previous activities of CGI or server-side script to do the chat room performance was on to die  .

    Push technology, chat rooms, chat rooms basic principle is  ,  HTTPD server program does not use  ,  Socket procedures by its own monitoring server on port 80  ,  According to standard html  ,  Receives a request to the browser  ,  Www server's response mimic  ,  Will chat back to the browser  .  It seems like in the browser page to browse a great page as always to receive state  .  That is  ,  We no longer use the CGI and other ways to handle the content of chat  ,  The use of our own procedures to deal with all matters  .  In fact, it is a dedicated chat server  ,  That is, a simplified WWW server specifically for chatting  .

    Discussing the specific program until the  ,  Let's look at the associated technical analysis  .

  ◆ http request and response process  

  http  Agreement between the browser and the WWW server communication standards  ,Socket  Chat server should abide by the agreement  .  Actually  ,  We only need to use a small part on it  .

  http  Use of the C  /S(  Client  /  Server  )  Mode ,  Which browser is the http client  ,  Browse a page is actually open a Socket connection  ,  Send a request to the WWW server  ,  The server sends the requested resource according to the response to the browser  ,  Then close the connection  .  Between the client and server requests and responses have a certain format requirements  ,  Just follow this format to receive a request to send response  ,  The browser will properly display the content you need  .

    Request and response have a similar structure  ,  Include  :

    * An initial line  

    * 0 or more header lines  

    * A blank line  

    *Optional message  

    We see how a browser sends a request  :

    When we visit the website http  ://www.somehost.com/path/file.html  When  ,  First, open a browser to the host www  .somehost.com  80 port socket  ,  Then send the following request  :

  GET /path/file.html HTTP/1.0

  From: [email protected]

  User-Agent: Mozilla/4.0 (compatible; MSIE 5.0; Windows NT 5.0; DigExt)

  [  Blank lines  ]

    The first line of GET  /path/file.html HTTP/1.0  We need to address the core  .  A space separated by a three-part  ,  Method  (method):GET,  Request Resources  :/path/file.html,http  Version  :HTTP/1.0.

    Server will be through the same socket with the following information to respond to  :

  HTTP/1.0 200 OK

  Date: Fri, 31 Dec 1999 23:59:59 GMT

  Content-Type: text/html

  Content-Length: 1354

  
  

Hello world!

( Other content )... The first line also consists of three parts :http Version , Status code , Associated with the status code description . Status code 200 that the request success . Complete response after sending message , The server will close the socket . ◆ server model Usually two major types of network server : (1) Cycle server (iterative server): It is a time server can only handle a request , Multiple requests to be placed in the same time the arrival of the request queue .TCP Socket server is rarely used cycle ways , Because if a customer and a problem with connection to the server , Will cause the entire server hangs . It is often used in server UDP socket . (2) Concurrent Server (concurrent server): Respectively, after the arrival of each request generates a new process to handle the request generated by the connection .TCP The Socket server with concurrent delivery of services most . Concurrent Server has a variety of ways : i Server and each client receives a connection , Create a new child process to deal with this client request . ii Server to create multiple child processes in advance , By this child process handling client requests . This approach is called " Pre-create (prefork)" Server . iii Select the server with the function to realize the multiplex multiple clients connected . iv Super Server (inet) Activation server . Concurrent server because of its algorithm and has the inherent advantages of fast response , And when a user communicate with the server deadlock will not affect other processes , However, multiple processes through inter-process communication between the realization of information exchange , And fork a new process brought about by the increase in overhead with increasing number of users , Therefore, the concurrent server is not necessarily the original is the best option .JAVA Language gives us the convenience of Thread , So that we can use multiple threads instead of multiple processes , Achieve concurrent server , Our rapid business development version of the chat rooms provide an advantage . It is worth noting , Under the linux ,JAVA There is no true multi-threaded , Essentially the process is still more . ◆ POST and GET Submission form commonly used form of information, there are two :POST Or GET .POST As the length of the unrestricted , As most of the methods used to submit form .GET Methods to send information submitted by URL , As the URL is WWW server limits the length of , Generally only up to 1024 bytes , Therefore, if long, then send a message , Can not use this method . As we chat with length , Not too long , Furthermore, general view page using GET method , Form using the GET method of form submission process can be simplified , So we can use this method to submit chat . We are fly in the ointment is the GET method to submit the contents of the simple connection attached to the back , If we can be submitted content HTML coding, then , Can give customers a comfortable points . ◆ Communication with JAVA SOCKET achieve concurrency If done before the SOCKET C Programming , Then this section of what you will not be difficult for . Using JAVA multi-threading can be very convenient mechanism to achieve concurrent services . When we know the server main program creates a new socket connection ( Accept the call successfully () Method ) When , To start a new thread to the server and the client is responsible for the connection between , Main program will go back and wait for the next connection . To achieve this program , The server should use the following form the main loop : while(true) { Socket newjoin=s.accept(); Tread t=new ThreadedChatHandle(newjoin); t.start(); } ThreadedChatHandle Class is derived from the Thread class subclass of the process of dealing with chat , It's run () Methods include the server and client communication cycle -- Determine customer's request ( For example, log . Speak . Refresh list online ), Statement data processing , Send chat messages, etc. . The following is an example of a server program , Can help beginners to understand as soon as possible . import java.io.*; import java.net.*; public class ChatServer { public static void main(String[] args) { int I=1; try {ServerSocket s=new ServerSocket(8080); /* Create a server socket monitoring port 8080 , If you need to , You can change port 80 */ for(;;) { Socket newjoin=s.accept(); /* Waiting for a connection . If this connection is not created , The method of blocking the current thread . Return value is a Socket Object , Server program can use this object to connect the customer communication .*/ System.out.println(" New Connection "+i); new ThreadedChatHandle(newjoin,i).start(); /* ThreadedChatHandle(Socket theS,int c) Is defined by our own chat service class , This Class in the back we have to further describe */ i++; } } catch(Exception e) { System.out.println(e); } } -- } Multi-process ( Thread ) Concurrent services is a key issue , How to implement process ( Thread ) Communication between . Each customer's statement ( Including options such as facial expressions and movements ) Needs in a public place , The output of all threads have access to it . There are many ways to solve , For example on the database , We have the rights on the dat file , Or directly with the pipeline to achieve inter-process communication . Among , Is a chat room server , The first method is the most stupid , Too much consumption of system resources , But also the efficiency of the program slow , More links can go wrong . Way communication using pipes , All speech data is stored in memory , Not only get the highest efficiency in the implementation , Security implementation , Need not consider the problem of thread synchronization . Do not think a lot of data of all the speeches , In fact, if the server save the last one hundred already is a fantastic , Not you ? JAVA In the API on the pipeline have : ● Java .io.PipedInputStream PipldInputStream(): Create a new channel input stream , And it does not pipe the output stream associated with a . PipldInputStream(PipldOutputStream out): Create a new channel input stream , And the output stream out from the pipe to read data . connect(PipldOutputStream out): Output stream associated with a pipe , And the stream to read data . ● Java .io.PipedOutputStream PipldOutputStream(): Create a new channel output stream , And it is not associated with a channel input stream . PipldOutputStream(PipldInputStream in): Create a new channel output stream , And output data to the in . connect(PipldInputStream in): Input stream associated with a pipe , And enter the data into in . ◆ Daemon Implementation Actually , I have not found directly in JAVA background daemon to implement the method . Background process to achieve a series of work needs to be done , Include : Close all the documents described in words : Change the current working directory : Reset file access mask code (umask) : In the background : From the process group : I ignored the terminal /O Signal : From the control terminal . JAVA There is a named DaemonThread thing , I have not used . According , This stuff is called service threads sole purpose is to provide services for other threads . And a service program in the thread if only if , This program will stop ( And our mind is simply nothing in ). Interested friends can see related content , In java .lang.Thread.setDaemon(). Although we can not achieve the background daemon JAVA , But we have the C interface to JAVA , The problem there is always a solution . ◆ exception handling Socket communication process in a very vulnerable to unexpected situations , If not addressed directly send data , May cause the program quit unexpectedly . Such as , After the client closed the socket , Server continues to send data , This can result in abnormal . To avoid this from happening , We have to deal with it , General , Simply ignore this signal can be a . Fortunately ,JAVA Exception handling mechanism is still relatively strong . ◆ users to judge and deal with disconnection Many cases , User is not by submitting " Leave " Button to leave the chat room , This time will need to determine whether the user disconnected . Break the average user may include the following situations : Is : When the user closes the browser , Or click the browser stop button , Or jump to other pages when ( If JAVASCRIPT up a chat window, then , So both cases we are able to avoid -- Big deal right then ban ), Corresponding to the socket will become readable state , Read out data at a time when the string is empty . Using this principle , As long as a readable socket read data , Data read is empty , Then we can conclude that , And the socket corresponding to the user disconnected . ◆ disconnected to prevent connection timeout If the browser for some time had not received any data , Then the time-out error occurs . To avoid this error , Must send some data within a certain interval , In our application where , Some html comments can be sent . Send comments directly into the chat work can be done between . Let us look at the specific implementation process : Chat server implementation The core part of our server is ThreadedChatHandle class , The data we need to address two main parts -- Online listings and user speak . Online list can use a large array of objects , This is based on a chat room capacity is limited consideration . The user's speech directly to the pipeline which can be a . Online list of categories are defined as follows : class Chater { private static Double id;// The ID number as the difference , At the same time private Double socketid; file:// And the main chat frame associated with the corresponding Socket . private String nickname;// User nickname private String passwd;// User nickname private Int privilige;// private String[] filter;// A user's filter list private Double login_time;// Record login time , Some overtime to clear the connection private String color;// Users chat color --// Space is limited , Related methods omitted . } Attention : Most of these user data in the login phase , After user authentication, enter the . Only socketid to wait until the main chat frame ( A common interface, including chat chat main frame , Speech frame , Online list frame of three parts ) Later be shown . If more than a certain time ,socketid Or not filled , Shows the main frame of the browser made after the connection was interrupted , This is when you need to remove the user data . If you want to achieve as a whisper, as if sohu , Should also increase the user IP address of the property . User speech class is defined as follows : class Content { private Double timestamp;// Timestamp private Double fromChaterid;// A spokesman for id private Double toChaterid;// Chatting id private Boolen isSecurity;// Logo whether whisper private String theContent;// Chats , Handled in the build-ri , Ht have included expressions such as ml Text . --// Space is limited , Related methods omitted . } Main processing core ThreadedChatHandle class work is to analyze user requests . Client sends the requested value , There are login ( Authentication , Shows the main framework of the chat room ).joinchat( Initialization chat message , Such as the Welcome , Show chat show frame , And stay connected , Send chat messages .).showtalk( Show floor frame ).names( Show frame-line list ).leave( Click the button to leave the chat room users ) Etc. . If we use the GET method to transfer data rather than through the POST method for form submission, then , User data input is transmitted in the URL in , Here are some examples of url , Combined with the back of the client process , Can better understand the functions of ThreadedChatHandle class : This is both a user name password 'aaa' Chat users log in , Said something "hello", Then generated a series of requests for withdrawal : /login?name=aaa&passwd=aaa /joinchat?chaterid=555 /showtalk?chaterid=555 /names?chaterid=555 /speak?chaterid=555 /leave?chaterid=555 -- These are the server program processes , In fact, we can not just pass the transmission parameters of achaterid , Also need to have a corresponding certificate . The names passed a chaterid time to update the list of categories in their online access time , Avoid connection timeout . Here we look at specific login from a client process . Chat interface formed by the three frame , One joinchat frame is part of chat show :showtalk Frame is part of the user input , Including chat input . Action . Filtering, and management input in the frame :names Is the online part of the list display , This section is regularly refreshed . Let the angle from the browser to see the process of entering the chat room . ◆ browser requests the first page http://host:8080/login?name=NAME&passwd=PWD At this point there a ThreadedChatHandle ( Includes a socket connection ), And send a line of data : GET /login?name=NAME&passwd=PWD HTTP/1.1 ◆ server generates a session id , After authentication password , Back : HTTP/1.1 200 OK < Other header information > Content-TYPE: text/html < Blank lines > -- -- Then ThreadedChatHandle .start() Quit , Thread end of the book ◆ browser after receipt of the above html file , Will in turn open the three links ( One is the need to pass the variable chaterid ,555 Is a virtual means ): /joinchat?chaterid=555 /showtalk?chaterid=555 /names?chaterid=555 The three join in the first link in the chat joinchat process is to keep connected , This point of view from a browser , Always download finish is a great page , Effect on the chat show is not on Refresh to update , But constantly scroll up . This html code can be seen through the , Only , Then there was the ever-increasing chats , No . The other two links in the page sent after completion of , Of the two threads on the end connection . Log In fact such a chat room to respond to four sub-thread , But the login is completed , Only the frame of the thread processing joinchat still alive , For receiving chat messages from the server , This is based on push technology the key to the chat room . Of course , If you have other requests for action , Such as user registration . Modify nickname . Modify password operation can be obtained by expanding the class corresponding to the response . Through the overloaded class methods can also be relatively easy to modify according to user authentication mechanisms and sites of other functional modules combined in a .
相关文章