Java Advanced--java Network programming

Source: Internet
Author: User

Java Network programming One, overview

  Network programming refers to writing programs that run on multiple devices (computers) that are connected through the network.

The J2SE API in the java.net package contains classes and interfaces that provide low-level communication details. You can use these classes and interfaces directly to focus on solving problems without focusing on the details of the communication.

The java.net package provides support for two common network protocols:   

      • TCP: TCP is an abbreviation for Transmission Control Protocol, which guarantees reliable communication between two applications. Usually used for Internet protocols, which are called TCP/IP.

      • UDP: UDP is the abbreviation of the User Datagram Protocol, a non-connected protocol. A packet that provides the data to be sent between applications.

Second,Socket programming

Sockets use TCP to provide a mechanism for communication between two computers. The client program creates a socket and tries to connect to the server's socket.

When the connection is established, the server creates a Socket object. The client and server can now communicate by writing and reading to the Socket object.

The Java.net.Socket class represents a socket, and the Java.net.ServerSocket class provides a mechanism for the server program to listen to the client and establish a connection with them.

The following steps occur when a TCP connection is established between two computers using sockets:    

      • The server instantiates a ServerSocket object that communicates through the port on the server.

      • The server calls the Accept () method of the ServerSocket class, and the method waits until the client connects to the given port on the server.

      • When the server is waiting, a client instantiates a Socket object, specifying the server name and port number to request a connection.

      • The constructor of the Socket class attempts to connect the client to the specified server and port number. If the communication is established, a Socket object is created on the client to communicate with the server.

      • On the server side, the Accept () method returns a new socket reference to the server that is connected to the client's socket.

After the connection is established, each socket has an output stream and an input stream by using the I/O stream, and the client's output is streamed to the server-side input stream, and the client's input is streamed to the server-side output stream.

1, the method of ServerSocket class

The server application obtains a port by using the Java.net.ServerSocket class and listens for client requests.

The ServerSocket class has four methods of construction:

Serial number Method description
1 public serversocket (int port) throws IOException
Creates a server socket bound to a specific port.
2 public ServerSocket (int port, int backlog) throws IOException
Creates a server socket with the specified backlog and binds it to the specified local port number.
3 public ServerSocket (int port, int backlog, inetaddress address) throws IOException
Creates a server using the specified port, the listener backlog, and the local IP address to bind to.
4 Public ServerSocket () throws IOException
Create a non-binding server socket.

Create a non-binding server socket. If the ServerSocket constructor method does not throw an exception, it means that your application has successfully bound to the specified port and listens for client requests.

Common methods of the ServerSocket class:

Serial number Method description
1 public int Getlocalport ()
Returns the port on which this socket listens.
2 Public Socket Accept () throws IOException
Listens for and accepts connections to this socket.
3 public void setsotimeout (int timeout)
Enables/disables so_timeout, in milliseconds, by specifying a time-out value.
4 public void bind (socketaddress host, int backlog)
Bind the ServerSocket to a specific address (IP address and port number).
2, the Socket class method

    The Java.net.Socket class represents a socket that both the client and the server use to communicate with each other. The client wants to get a socket object by instantiating it, and the server obtains a socket object through the Accept () method's return value.

The Socket class has five construction methods    

ordinal method Description
1 public Socket (String host, int port) throws Unknownhostexception, IOException. The
creates a stream socket and connects it to the specified port number on the specified host.
2 public Socket (inetaddress host, int port) throws IOException
Create a stream socket and connect it to the specified port number for the specified IP address.
3 public Socket (String host, int port, inetaddress localaddress, int local Port) throws IOException. The
creates a socket and connects it to the specified remote port on the specified remote host.
4 public Socket (inetaddress host, int port, inetaddress localaddress, int LocalPort) throws IOException. The
creates a socket and connects it to the specified remote port on the specified remote address.
5 public sockets ()
Create an SocketImpl socket from the system default type

When the socket construction method returns, and does not simply instantiate a socket object, it will actually attempt to connect to the specified server and port.

Note Both the client and server side have a Socket object, so these methods can be invoked both by the client and the service side.

Serial number Method description
1 public void Connect (socketaddress host, int timeout) throws IOException
Connect this socket to the server and specify a timeout value.
2 Public inetaddress getinetaddress ()
Returns the address of the socket connection.
3 public int Getport ()
Returns the remote port that this socket is connected to.
4 public int Getlocalport ()
Returns the local port to which this socket is bound.
5 Public socketaddress getremotesocketaddress ()
Returns the address of the endpoint for this socket connection, or null if not connected.
6 Public InputStream getInputStream () throws IOException
Returns the input stream for this socket.
7 Public OutputStream Getoutputstream () throws IOException
Returns the output stream for this socket.
8 public void Close () throws IOException
Close the socket.

   

3, the method of InetAddress class

This class represents an Internet Protocol (IP) address. The following is a list of the more useful methods for Socket programming:

      

Serial number Method description
1 Static InetAddress getbyaddress (byte[] addr)
Returns the InetAddress object, given the original IP address.
2 Static InetAddress getbyaddress (String host, byte[] addr)
Creates a inetaddress based on the host name and IP address provided.
3 Static InetAddress Getbyname (String host)
Determines the IP address of the host in the given host name.
4 String gethostaddress ()
Returns the IP address string (in text representation).
5 String GetHostName ()
Gets the host name for this IP address.
6 Static InetAddress Getlocalhost ()
Returns the local host.
7 String toString ()
Convert this IP address to a String.
4. Socket Client Instance

The following greetingclient is a client program that connects to the server via the socket and sends a request, and then waits for a response.

1 //file name Greetingclient.java2  3 Importjava.net.*;4 ImportJava.io.*;5  6  Public classgreetingclient7 {8     Public Static voidmain (String [] args)9    {TenString ServerName = args[0]; One       intPort = Integer.parseint (args[1]); A       Try -       { -SYSTEM.OUT.PRINTLN ("Connect to Host:" + ServerName + ", port number:" +port); theSocket client =NewSocket (ServerName, port); -SYSTEM.OUT.PRINTLN ("Remote host Address:" +client.getremotesocketaddress ()); -OutputStream Outtoserver =Client.getoutputstream (); -DataOutputStream out =NewDataOutputStream (outtoserver); +   -Out.writeutf ("Hello from" +client.getlocalsocketaddress ()); +InputStream Infromserver =Client.getinputstream (); ADataInputStream in =NewDataInputStream (infromserver); atSYSTEM.OUT.PRINTLN ("Server response:" +In.readutf ()); - client.close (); -}Catch(IOException e) -       { - e.printstacktrace (); -       } in    } -}
5. Socket Server Instance

The Greetingserver program below is a server-side application that uses a Socket to listen on a specified port.

1 //file name Greetingserver.java2  3 Importjava.net.*;4 ImportJava.io.*;5  6  Public classGreetingserverextendsThread7 {8    PrivateServerSocket ServerSocket;9    Ten     PublicGreetingserver (intPortthrowsIOException One    { AServerSocket =NewServerSocket (port); -Serversocket.setsotimeout (10000); -    } the   -     Public voidRun () -    { -        while(true) +       { -          Try +          { ASystem.out.println ("Wait for remote connection, port number:" + serversocket.getlocalport () + "..."); atSocket Server =serversocket.accept (); -SYSTEM.OUT.PRINTLN ("Remote host Address:" +server.getremotesocketaddress ()); -DataInputStream in =NewDataInputStream (Server.getinputstream ()); - System.out.println (In.readutf ()); -DataOutputStream out =NewDataOutputStream (Server.getoutputstream ()); -Out.writeutf ("Thank You for connecting me:" + server.getlocalsocketaddress () + "\ngoodbye!"); in server.close (); -}Catch(sockettimeoutexception s) to          { +System.out.println ("Socket timed out!"); -              Break; the}Catch(IOException e) *          { $ e.printstacktrace ();Panax Notoginseng              Break; -          } the       } +    } A     Public Static voidmain (String [] args) the    { +       intPort = Integer.parseint (args[0]); -       Try $       { $Thread T =NewGreetingserver (port); - T.run (); -}Catch(IOException e) the       { - e.printstacktrace ();Wuyi       } the    } -}

Compile the above two Java file code and execute the following command to start the service with a port number of 6066:

6066 waiting for remote connection, port number is:6066 ...

Open a new command window and execute the above command to open the client:

6066 connect to host: localhost, port number:6066 remote host address: localhost/127.0.0.1:6066 server response: Thank you for connecting me:/ 127.0.0.1:6066Goodbye!

Java Advanced--java Network programming

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.