Implementation of technical chat room (on)

zhaozj2021-02-08  328

Sender: Luckyboy (the sea is going to the end), the letter area: NetWork Title: Implementation of the technology chat room (on) Chat room based on push technology is now more common in China. The biggest feature of this chat room is to refresh the way for a browser for a period of time, and let the server write chat on the client. When someone speaks, there will be new chat content on the screen, and chat content is constantly scrolling. If the browser status bar is in, you can see the progress bar is always downloaded. Even if this chat room is accommodated, the performance will not be significantly reduced. The chat room performance that the past CGI or active server side script is obvious. The basic principle of the chat room chat room is that the HTTPD server program is not used, and the 80-port of the server is listened by its own socket program. After the HTML specification, after the request of the browser, the response of the WWW server will be used, and the contents of the WWW server will chat. Send back the browser. In the browser, it is always on the page reception status like browsing a huge page. That is, we no longer use CGI and other ways to process the contents of chat, and use our own programs to handle all transactions. In fact it is a specialized chat server, a simplified WWW server that is specifically used to chat. Before the implementation of the specific discussion program, let's first analyze the relevant technologies. ◆ The HTTP request and response process The HTTP protocol is a standard that the browser communicates with the WWW server, and the Socket chat server should follow this protocol. In fact, we only need to use a small part of them. HTTP uses a C / S (client / server) mode, where the browser is an HTTP customer. Browse a page actually opens a socket connection, send a request to the WWW server, the server sends a response to the browser according to the requested resource Then close the connection. The request and response between the client and the server have certain format requirements, as long as the request send a response is received according to this format, the browser will display the content you need. Requests and answers have similar structures, including: • An initial line · 0 or more header lines · A blank line · Optional information Let's take a look at a browser: When we browse the web http: // www .SomeHost.com / path / file.html, the browser first opens a socket to the 80 port of the host www.somehost.com, then send the following request: get /path/file.html http / 1.0 from: Someuser @ Somehost.com User-Agent: Mozilla / 4.0 (Compatible; Msie 5.0; Windows NT 5.0; DiGext) [Dark Block] The first line Get /Path/File.html http / 1.0 is the core we need to process. Method (Method): Get, request resources: /path/file.html, http version: http / 1.0.

The server will respond through the same SOCKET: 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 includes three parts: HTTP version, status code, description related to the status code. Status code 200 indicates successful request. After sending the response information, the server will close the socket. ◆ Server model General web server is mainly divided into two: (1) ITERATIVE Server: It is a time that can only handle a request, multiple requests will be placed in the request queue at the same time. TCP socket servers typically use a loop mode, because if a customer and server connection has a problem, it will cause the entire server to hang. It is often used for UDP socket servers. (2) Concurrent Server: Generate a new process after each request, to process the connection generated by this request. Most of the TCP's Socket Server uses concurrently available services. The concurrent server has a variety of implementation methods: i servers and each received client, create a new sub-process to process this client request. The II server is created in advance, and the client request is handled by this sub-process. This approach is called a "prefork" server. III Server Function SELECT implements multiple multiplexes connected to multiple clients. IV Super Server (inet) activated server. The concurrent server has a new fast response advantage due to its algorithm, and when a user and server communication deadlock does not affect other processes, but due to multiple processes need to exchange information exchange, and fork The overhead brought about by the new process has increasing the number of users, so the original concurrent server is not necessarily the best choice. The Java language gives us the convenient thread mechanism that allows us to replace multiple processes in multithreading, providing concurrent servers, providing an advantage for the development of our fast business versions of chat room. It is worth noting that under Linux, Java does not implement real multi-threads, essentially a multi-process. ◆ POST and GET Submit Form form information is commonly commonly used: POST or GET. POST is used as a method used in most Form submission due to the length of the form. The GET method sends submission information through the URL. Since the URL is limited by the WWW server, the length can only be 1024 bytes, so this method cannot be used if the message is transmitted. Since we have a length limit on chat content, it will not be too long, and the normal browsing page uses a GET method, use the GET method to submit the Form form to simplify the process, so we can use this method to submit chat content. We feel that the GET method is a simple connection to the connection, and if we can make HTML encoding, we can make our customers comfort. ◆ Use Java to implement concurved SOCKET communication If you have done C's Socket programming, then this paragraph will not be difficult for you. Using Java multi-thread mechanism we can easily implement concurrent services.

Whenever we know that the server main program creates a new socket connection (that is, when the Accept () method is successfully called), start a new thread to be responsible for the connection between the server and the customer, the main program will Return and wait for the next connection. In order to achieve this program, the main loop of this server should use the following form: while (true) {socket newjoin = S.Accept (); Tread T = new threadedchathandle (newjoin); t.start ();} ThreadedChathandle class is from Thread class The subclass of derived chat processes, its Run () method includes communication cycles of servers and customers - judges the customer's request (eg, login, speech, refresh list), processing speaking data, send chat information, etc. . Below is an example of a server program, you can help beginners 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 monitoring 8080 port server socket, if needed, you can change to 80 port * / for (;;) {socket newjoin = S.Accept (); / * Wait a connection. If this connection is not created, this method blocks the current thread. The return value is a socket object, and the server program uses this object to communicate with the connected customer. * / System.out.println ("New Connection" i); New Threadedchathandle (NewJoin, i) .Start (); / * ThreadedChathandle (Socket S, INT C) is our own Chat Service Class, this class is Behind we have further describe * / i ;}} catch (exception e) {system.out.println (e);}} ...} A key issue for multi-process (thread) concurrent services is how to implement the process (thread) Inter-communication. Each customer's statement (including the options such as expression and action) requires a public place to get all the output threads. There are a lot of ways to solve, for example, in the database, put in a DAT file that everyone has permission, or direct communication between the processes directly. Among them, the first method is the most stupid, too consumes system resources, and makes the program execution efficiency, possibly increased. The way of using pipe communication, saving all speaking data in memory, not only can you get the highest execution efficiency, security execution process, but also do not need to consider the problem of thread synchronization. Don't think that all of the speeches will be a lot, in fact, the server side is already very can't save the last 100 sentences, isn't it? The API of the pipeline in Java has: ● java.io.pipedinputStream PipldInputStream (): Create a new pipe input stream, and it does not associate a pipe output stream. PIPLDINPUTSTREAM (PIPLDOUTPUTSTREAM OUT): Create a new pipe input stream and read data from the pipe output stream OUT.

Connect (PiPLDOutputStream Out): Associa a pipe output stream, and this stream reads data. ● java.io.pipedputstream pipldoutputStream (): Create a new pipe output stream, and it does not associate a pipe input stream. PIPLDOUTPUTSTREAM (PIPLDINPUTSTREAM IN): Create a new pipe output stream and output data to IN. Connect (PIPLDINPUTSTREAM IN): Associates a pipe input stream and entering data to IN. ◆ DAEMON's implementation actually, I haven't found a way to implement the background daemon directly in Java. Implement a set of works need to complete a range of work, including: Turn off all file descriptors; change the current work directory; reset file access shielding code (UMASK); execute in the background; detachment group; ignore the terminal I / O signal Draway from the control terminal. There is a thing called Daemon Thread in Java, I have not used it. According to reports, the only purpose of the Dongdong of this calling service thread is to provide services for other threads. And if there is only a service thread in a program, this program will stop (and our original intention is simply in the north). Interested friends can look at the relevant content, in java.lang.thread.setdaemon (). Although we cannot use Java to implement the background service daemon, we have Java's C interface, and there is always a solution. ◆ Exception handling is easy to appear in the Socket communication process, and if it is not processed, directly send data, it may cause an accident to exit. For example, after the customer closes the socket, the server continues to send data, which will cause an exception. In order to avoid this, we must handle it, in general, just simply ignore this signal. Fortunately, Java's abnormal handling mechanism is also quite strong. ◆ User disconnection judgment and handling Many cases, users are not to leave the chat room by submitting the "Leave" button, at this time, it is necessary to determine whether the user is disconnected. The general user disconnection may include the following cases: the method is: When the user closes the browser, or click the browser STOP button, or if you jump to other pages (if you use JavaScript to pop up a chat window, then these two Situation We are able to avoid the right buse, which will turn right back), and the corresponding Socket will become a readable state, and the data read at this time is an empty string. With this principle, as long as you read data on a readable socket, you can conclude that the user is disconnected from this socket. ◆ Prevent connection timeout disconnection If the browser does not receive any data for a while, the timeout error will occur. To avoid this error, you must send some data within a certain interval. In our application, you can send some HTML comments. The job of sending comments can be done directly between chat content.

转载请注明原文地址:https://www.9cbs.com/read-906.html

New Post(0)