Java Network programming

Source: Internet
Author: User

Java Network Programming

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.

This tutorial focuses on the following two topics.

    • Socket Programming : This is the most widely used network concept and it has been explained in very detailed
    • URL processing : This part will be said in another space
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, the communication is made by using the I/O stream. Each socket has an output stream and an input stream. 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.

TCP is a two-way communication protocol, so data can be sent over two data streams at the same time. The following are a complete set of useful methods provided by some classes to implement sockets.

Methods of the 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:

 PublicServerSocket (intPortthrowsIOException creates a server socket bound to a specific port.
PublicServerSocket (intPortintBacklogthrowsIOException creates a server socket with the specified backlog and binds it to the specified local port number.
PublicServerSocket (intPortintBacklog, inetaddress address)throwsIOException creates the server with the specified port, the listening backlog, and the local IP address to bind to.
PublicServerSocket ()throwsIOException Create a non-binding server socket.

Common methods of the ServerSocket class:

 Public int getlocalport ()     returns the port on which this socket listens.  publicthrows  IOException    listens for and accepts connections to this socket.  publicvoid setsotimeout (int timeout)   enables/ disables so_timeout, in milliseconds, by specifying a timeout value  publicvoidint backlog) binds serversocket to a specific address (IP address and port number).

Method of Socket Class

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 constructor methods.

 PublicSocket (String host,intPortthrowsunknownhostexception, IOException. Creates a stream socket and connects it to the specified port number on the specified host.  PublicSocket (inetaddress host,intPortthrowsIOException creates a stream socket and connects it to the specified port number for the specified IP address.  PublicSocket (String host,intPort, InetAddress localaddress,intLocalPort)throwsIOException. Creates a socket and connects it to the specified remote port on the specified remote host.  PublicSocket (inetaddress host,intPort, InetAddress localaddress,intLocalPort)throwsIOException. Creates a socket and connects it to the specified remote port on the specified remote address.  Publicsocket () creates 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.

Here are some interesting ways to note that both the client and server side have a socket object, so the methods can be invoked both by the client and the service side.

 Public voidConnect (socketaddress Host,intTimeoutthrowsIOException Connect this socket to the server and specify a timeout value.  Publicinetaddress getinetaddress () returns the address of the socket connection.  Public intGetport () returns the remote port that this socket is connected to.  Public intGetlocalport () returns the local port to which this socket is bound.  PublicSocketAddress getremotesocketaddress () returns the address of the endpoint of this socket connection and returns if not connectedNULL.  PublicInputStream getInputStream ()throwsIOException returns the input stream for this socket.  PublicOutputStream Getoutputstream ()throwsIOException returns the output stream for this socket.  Public voidClose ()throwsIOException close this socket.

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.

//file name Greetingclient.javaImportjava.net.*;ImportJava.io.*;  Public classgreetingclient{ Public Static voidmain (string [] args) {string ServerName= Args[0]; intPort = Integer.parseint (args[1]); Try{System.out.println ("Connecting to" +ServerName+ "on port" +port); Socket Client=NewSocket (ServerName, Port); System.out.println ("Just connected to" +client.getremotesocketaddress ()); OutputStream Outtoserver=Client.getoutputstream (); DataOutputStream out=NewDataOutputStream (Outtoserver); Out.writeutf ("Hello from" +client.getlocalsocketaddress ()); InputStream Infromserver=Client.getinputstream (); DataInputStream in=NewDataInputStream (Infromserver); System.out.println ("Server says" +In.readutf ());      Client.close (); }Catch(IOException e) {e.printstacktrace (); }   }}
View Code

Socket Service-side instance

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

//file name Greetingserver.javaImportjava.net.*;ImportJava.io.*; Public classGreetingserverextendsthread{PrivateServerSocket ServerSocket;  PublicGreetingserver (intPortthrowsIOException {serversocket=NewServerSocket (port); Serversocket.setsotimeout (10000); }    Public voidrun () { while(true)      {         Try{System.out.println ("Waiting for client on port" +Serversocket.getlocalport ()+ "..."); Socket Server=serversocket.accept (); System.out.println ("Just connected to" +server.getremotesocketaddress ()); DataInputStream in=NewDataInputStream (Server.getinputstream ());            System.out.println (In.readutf ()); DataOutputStream out=NewDataOutputStream (Server.getoutputstream ()); Out.writeutf ("Thank connecting to" + server.getlocalsocketaddress () + "\ngoodbye!");         Server.close (); }Catch(sockettimeoutexception s) {System.out.println ("Socket timed out!");  Break; }Catch(IOException e) {e.printstacktrace ();  Break; }      }   }    Public Static voidmain (String [] args) {intPort = Integer.parseint (args[0]); Try{Thread T=NewGreetingserver (port);      T.start (); }Catch(IOException e) {e.printstacktrace (); }   }}
View Code

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

$ java greetingserver 6066 for client on port 6066 ...

Turn on the client as follows:

$ java greetingclient localhost 60666066Just connected to localhost/127.0.0.1:6066for connecting to/127.0.0.1:6066Goodbye!

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.