A simple server and client program

Source: Internet
Author: User
Tags finally block readline reserved socket tostring port number

The

Example will use sockets to manipulate the server and the client in the simplest way. The whole job of the server is to wait to establish a connection and then create a inputstream and a outputstream with the socket that the connection produces. After that, everything it reads from the InputStream is fed back to OutputStream until the line abort (end) is received, and the connection is closed. The
client connects to the server and then creates a outputstream. The line of text is sent by OutputStream. The client also creates a inputstream and uses it to listen to what the server is saying (this example is just the same word as feedback). The
Server and Client (program) Use the same port number. And the client connects to the server (program) in the same machine using the local host address, so it is not necessary to complete the test on a physical network (in some configuration environments, you may need to connect to a real network or the program will not work – Although it does not actually communicate through that network.
The following are server programs:

 

: Jabberserver.java//Very simple server that just//echoes whatever the client sends.
Import java.io.*;

Import java.net.*;
  public class Jabberserver {//Choose a port outside of the range 1-1024:public static final int port = 8080;
    public static void Main (string[] args) throws IOException {ServerSocket s = new ServerSocket (PORT);
    System.out.println ("started:" + s);
      try {//Blocks until a connection occurs:socket Socket = S.accept ();
        try {System.out.println ("Connection accepted:" + socket); BufferedReader in = new BufferedReader (New InputStreamReader Socket.getinputstream (
        )));
            Output is automatically flushed//by printwriter:printwriter out = new PrintWriter (
        New BufferedWriter (New OutputStreamWriter (Socket.getoutputstream ()), true); while (true) {String str =In.readline ();
          if (Str.equals ("End")) a break;
          System.out.println ("Echoing:" + str);
        Out.println (str); }//Always Close the two sockets ...}
        finally {System.out.println ("closing ...");
      Socket.close ();
    finally {s.close (); }
  } 
} ///:~


As you can see, ServerSocket needs only a port number and does not need an IP address (because it runs on this machine). When accept () is invoked, the method is temporarily stalled (blocked) until a client attempts to establish a connection with it. In other words, although it is there to wait for the connection, other processes can still function (refer to chapter 14th). After building a connection, accept () returns a socket object, which is the representative of that connection.
The responsibility to clear the socket has been handled very artistically here. If the ServerSocket builder fails, the program simply exits (note that you must ensure that the ServerSocket builder does not leave any open network sockets after the failure). In this case, main () throws a ioexception violation, so you do not have to use a try block. If the ServerSocket builder succeeds, all other method calls must be protected in a try-finally code block to ensure that the serversocket is properly closed regardless of how the block is left.
The same principle applies to the socket returned by accept (). If accept () fails, then we must ensure that the socket no longer exists or contains any resources so that it does not have to be purged. However, if the execution succeeds, the subsequent statements must be entered into a try-finally block to ensure that the socket can still be properly cleared in case they fail. Because sockets use important, non-memory resources, you must be cautious here and have to clean them yourself (there is no "sabotage" provided in Java to help us do this).
Either ServerSocket or the socket produced by accept () is printed into the System.out. This means that their tostring method is automatically invoked. This creates the following:

SERVERSOCKET[ADDR=0.0.0.0,PORT=0,LOCALPORT=8080]
socket[addr=127.0.0.1,port=1077,localport=8080]


You will soon see how they work with the client program.
the next part of the program appears to be simply opening the file for reading and writing, except that InputStream and OutputStream are created from the socket object. The two converters class InputStreamReader and Outputstreamwriter,inputstream and OutputStream objects have been converted to Java 1.1 reader and writer objects respectively. It is also possible to use the Java1.0 InputStream and OutputStream classes directly, but for the output, using the writer method has obvious advantages. This advantage is represented by PrintWriter, which has an overloaded builder that gets the second argument-a Boolean flag that points to whether the output is automatically refreshed at the end of each println (but not the print () statement). Each time the output is written (written out), its buffer must be refreshed so that the information can be officially passed through the network. For the current example, refreshing is particularly important because customers and servers wait for the arrival of a line of text before taking the next step. If the refresh does not occur, then the information will not go into the network unless the buffer is full (overflow), which poses many problems for this example.
When writing a network application, you need to pay special attention to the use of the automatic refresh mechanism. Each time the buffer is refreshed, a packet (data block) must be created and emitted. In the present case, this is exactly what we want, because if the package contains a line of text that has not yet been issued, the "handshake" between the server and the client will stop. In other words, the end of a line is the end of a message. In many other cases, however, messages are not separated by rows, so it is better to use the built-in buffer decision mechanism to decide when to send a packet instead of the automatic refresh mechanism. In this way, we can send out larger packets, and the processing process can also be speeded up.
Note that, like almost any data stream we open, they are buffered. There is an exercise at the end of this chapter that clearly shows what happens if we do not buffer the data stream (the speed slows). The
Infinite while loop reads the lines of text from BufferedReader in, writes the information to System.out, and writes the printwriter.out. Note that this can be any data flow, and they are only connected to the network on the surface. When the
client issues a row that contains "end", the program aborts the loop and closes the socket.
The following is the source code for the client program:

 

: Jabberclient.java//Very simple client, just sends//lines to the server and reads lines/that the server Sen
Ds.
Import java.net.*;

Import java.io.*; public class Jabberclient {public static void main (string[] args) throws IOException {//passing NULL to GE Tbyname () produces the The//special "local loopback" IP addresses, for//testing on one machine w/o a network:in
    Etaddress addr = Inetaddress.getbyname (null); Alternatively, can use//the address or name://InetAddress addr =//Inetaddress.getbyname ("127
    .0.0.1 ");
    InetAddress addr =//Inetaddress.getbyname ("localhost");
    System.out.println ("addr =" + addr);
    Socket socket = new socket (addr, jabberserver.port); Guard everything in a try-finally to make//sure that's the socket is closed:try {System.out.println ("so
      Cket = "+ socket); BufferedReader in = new BufferedReader (New InputstreaMreader (Socket.getinputstream ()));  Output is automatically flushed//by printwriter:printwriter out = new PrintWriter (new
      BufferedWriter (New OutputStreamWriter (Socket.getoutputstream ()), true);
        for (int i = 0; i < i + +) {out.println ("howdy" + i);
        String str = in.readline ();
      System.out.println (str);
    } out.println ("End");
      finally {System.out.println ("closing ...");
    Socket.close (); }
  }
} ///:~


In main (), you can see three ways to get the inetaddress of the local host IP address: Use NULL, use localhost, or use the reserved address 127.0.0.1 directly. Of course, if you want to connect to the same remote host over the network, you can also swap the IP address of that machine. After printing out the InetAddress addr (via an automatic call to the ToString () method), the results are as follows:
localhost/127.0.0.1
By passing a null to Getbyname (), it finds the localhost by default and generates a special reserved address 127.0.0.1. Note that when a socket named socket is created, both inetaddress and the port number are used. When printing a socket object like this, to really understand what it means, remember that a unique Internet connection is identified with the following four data types: ClientHost (client host), Clientportnumber (client-side slogan), ServerHost (service Host) and Serverportnumber (service port number). When the service program is started, it is assigned a port (8080) on the local host (127.0.0.1). Once the client makes a request, the next available port on the machine is assigned to it (in this case 1077), which is also performed on the same machine (127.0.0.1) as the service program. Now, in order for data to be sent back and forth between customers and service programs, each end needs to know where to send the data. So when the same "known" service program is connected, the customer sends a "return address" to let the server program know where to send its data. We can experience this in the server-side demonstration output:
SOCKET[ADDR=127.0.0.1,PORT=1077,LOCALPORT=8080]
This means that the server has just accepted a connection from port 1077 of the 127.0.0.1 machine, while listening on its own local port (8080). And at the client:
SOCKET[ADDR=LOCALHOST/127.0.0.1,PORT=8080,LOCALPORT=1077]
This means that the customer has established a connection with port 8080 on the 127.0.0.1 machine with its own local port 1077.
You will notice that the local port number increases each time the client is restarted. This number starts at 1025 (just over 1-1024 of the system reservation) and continues to increase until we reboot the machine. If you restart the machine, the port number will still add value from 1025 (in a UNIX machine, the number will again start with the smallest available number once it has exceeded the reserved set-word range).
After you create a good socket object, the process of converting it to BufferedReader and PrintWriter is the same as in the server (and, in both cases, starting with a socket). Here, the customer initiates the communication by emitting a string "Howdy" followed by a number following it. Note that the buffer must be refreshed again (this occurs automatically by passing to the second parameter of the PrintWriter builder). If the buffer is not refreshed, the entire session (communication) is suspended because the "howdy" used for initialization is never sent out (the buffer is not full enough to cause the send action to be automatic). Each row returned from the server is written to System.out to verify that everything is working properly. An "end" is required to abort the session. If the client program simply hangs, the server "throws" a violation.
As you can see here we have taken the same steps to ensure that the network resources represented by the socket are properly cleared, and this is done with a try-finally block.
The socket establishes a "private" connection that lasts until it is explicitly disconnected (the private connection may also be disconnected indirectly, if one end or one of the middle links fails). This means that both parties involved in the connection are locked in communication, and the connection is continuously open regardless of whether there is data transfer. From the surface, this seems to be a reasonable way of networking. However, it also brings additional overhead to the network. Another way to do networking is described later in this chapter. In that way, the connection is established only temporarily.

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.