Java socket programming notes

Source: Internet
Author: User

Compared with C and C ++, socket programming in Java is relatively simple, and many details have been encapsulated. Each time you create a socket connection, you only need to know the address and port. Before learning about socket programming, let's take a look at some of the things you need to pay attention to when reading and writing data streams. The difference between BufferedReader and DataInputStream: The Byte input and output streams we commonly use include BufferedReader and PrintWriter, DataInputStream, and DataOutputStream. These classes all belong to java. io packages. So what is the difference between the two? The difference is that the former has a buffer. If we set it to 100 kb manually (not set, there is a default value), when the content stored in the buffer reaches kb, class Object. The two objects of Stream do not have a buffer. They read and write data immediately after receiving data. Therefore, during socket programming, it is best not to use these two pairs in turn, because when data is stored in the cache mentioned above, stream objects cannot read in the cache, therefore, data may be lost. Here we also talk about the PrintWriter class. Let's first look at two common constructor Methods: In the second constructor, parameter 2 indicates whether the object will automatically fl the data streams in the buffer zone, in general, we can use the second constructor to set parameter 2 to true. Otherwise, the flush method will be followed every time the PrintWriter object is used to call the printXXX method. For example: PrintWriter pw = new PrintWriter (socket. getOutputStream); pw. println ("Write Data"); pw. flush (); if you do not do this, the pw object may not perform any operation because the data you want to write has not reached the specified size in the buffer. At this time, your thread will be blocked !! So be careful about this. Socket working mode in Java: We basically need to use these classes in socket programming: SocketServer, Socket, BufferedReader and PrintWriter (or DataInputStream and DataOutputStream ). On the server, first create a server socket object: ServerSocket srvSocket = new ServerSocket (nPort); once the request is received, generate a socket object: Socket socket = srvSocket. accept (); then create a stream object: BufferedReader bf = new BufferedReader (new InputStreamReader (socket. getInputStream (); PrintWriter pw = new PrintWriter (socket. getOutputStream (), true); connect directly to the client and create a stream object: Socket socket = new Socket (hostAddr, nPort); Socket programming basics Java Implementation: in fact, in the implementation process, I encountered a lot of details, but it was very painful. For example, the previously mentioned PrintWriter object is set to automatically fl out the cache content during initialization, or the flush method is called after each write operation. The following shows the implementation method: client implementation: The function implemented by the client is as follows: Enter some specific strings, such as DATE, BYE, DOY, DOM, and DOW, then let the server determine what command is entered, and then the server calls the Calendar class to return the corresponding date and time information. I want to read user input information from the console, So I designed the following code: copy the code BufferedReader inSys = new BufferedReader (new InputStreamReader (System. in); while (string = inSys. readLine ())! = Null & string. length ()! = 0) {System. out. println ("the command entered on the client side is" + string); pw. println (string); System. out. println ("the data returned by the server is" + bf. readLine (); // ctrl + z or Enter to terminate the loop}. If you press ctrl + z or Enter, the loop ends. The complete implementation Code of the client is given below: View Code server implementation: when designing the server, the Runnable interface is applied to the class of data read/write operations, so that multithreading can be realized, because the server does not provide services only to one client, you can directly write multi-threading when writing the exercise program. It is not necessary to start from the basic practice and the progress is too slow. In the master method of the server, we continuously accept new connection requests through an infinite loop: copy the code ServerSocket srvSocket = new ServerSocket (8888); while (true) // The server must be running all the time, so that it can continuously listen to and receive new socket connections {Socket socket = srvSocket. accept (); // receives the new request System. out. println ("new socket connection request received"); ServerThread sThread = new ServerThread (socket); Thread thread = new Thread (sThread); thread. start (); // the preceding three lines of code can be directly written as: // new Thread (new ServerThread (socket )). start ();} copy the code Then, the server can continue running. The specific operation data method can be written in the run method inherited from the interface. This method must be overloaded.

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.