Overview
Network programming refers to writing programs that run on multiple devices (computers) that are connected through the network.
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.
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. TCP is a two-way communication protocol, so data can be sent over two data streams at the same time. Here are some classes that provide a complete set of useful ways to implement a socket.
ServerSocket
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:
//creates a server socket bound to a specific port. PublicServerSocket (intport) throws IOException//creates a server socket with the specified backlog and binds it to the specified local port number. PublicServerSocket (intPortintbacklog) throws IOException//creates a server using the specified port, the listener backlog, and the local IP address to bind to. PublicServerSocket (intPortintbacklog, inetaddress address) throws IOException//Create a non-binding server socket. PublicServerSocket () throws IOException
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. Here are some common methods for ServerSocket classes:
//returns the port on which this socket listens. Public intGetlocalport ()//listens for and accepts connections to this socket. PublicSocket Accept () throws IOException//Enables/disables so_timeout, in milliseconds, by specifying a time-out value. Public voidSetsotimeout (intTimeout)//bind the ServerSocket to a specific address (IP address and port number). Public voidBind (SocketAddress host,intBacklog
Socket
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.
//creates a stream socket and connects it to the specified port number on the specified host. PublicSocket (String host,intport) throws Unknownhostexception, IOException.//creates a stream socket and connects it to the specified port number for the specified IP address. PublicSocket (inetaddress host,intport) throws IOException//creates a socket and connects it to the specified remote port on the specified remote host. PublicSocket (String host,intPort, InetAddress localaddress,intLocalPort) throws IOException.//creates a socket and connects it to the specified remote port on the specified remote address. PublicSocket (inetaddress host,intPort, InetAddress localaddress,intLocalPort) throws IOException.//Create an SocketImpl socket from the system default type PublicSocket ()
Socket common methods
//Connect This socket to the server and specify a timeout value. Public voidConnect (socketaddress Host,inttimeout) throws IOException//returns the address of the socket connection. Publicinetaddress getinetaddress ()//returns the remote port that this socket is connected to. Public intGetport ()//returns the local port to which this socket is bound. Public intGetlocalport ()//returns the address of the endpoint for this socket connection, or null if not connected. Publicsocketaddress getremotesocketaddress ()//returns the input stream for this socket. PublicInputStream getInputStream () throws IOException//returns the output stream for this socket. PublicOutputStream Getoutputstream () throws IOException//close the socket. Public voidClose () throws IOException
Methods of the InetAddress class
//returns the InetAddress object, given the original IP address. StaticInetAddress getbyaddress (byte[] addr)//creates a inetaddress based on the host name and IP address provided. StaticInetAddress getbyaddress (String host,byte[] addr)//determines the IP address of the host in the given host name. Staticinetaddress Getbyname (String host)//returns the IP address string (in text representation). String gethostaddress ()//gets the host name for this IP address. String gethostname ()//returns the local host. Staticinetaddress getlocalhost () String toString ()
code example
ServerSocket
Package Commclass;import java.io.datainputstream;import java.io.dataoutputstream;import java.io.IOException; Import Java.net.serversocket;import java.net.Socket; Public classGreetingserver {PrivateServerSocket ServerSocket; PublicGreetingserver (intPort) throws Exception {ServerSocket=NewServerSocket (port); Serversocket.setsotimeout (10000); } Public voidrun () { while(true) { Try{System. out. println ("waiting for client on port"+serversocket.getlocalsocketaddress ()); Socket Server=serversocket.accept (); System. out. println ("Just connected to"+server.getremotesocketaddress ()); DataInputStreaminch=NewDataInputStream (Server.getinputstream ()); System. out. println ("Client Say:"+inch. readUTF ()); DataOutputStream out=NewDataOutputStream (Server.getoutputstream ()); out. writeUTF ("Hi,service is Ok"+server.getlocaladdress ()); Server.close (); } Catch(Exception ex) {ex.printstacktrace (); } } } }
Clientsocket
Package Commclass;import java.io.datainput;import java.io.datainputstream;import java.io.DataOutputStream; Import Java.io.inputstream;import java.io.outputstream;import java.net.Socket; Public classClientsocket { Public Static voidconnclient (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 (); DataInputStreaminch=NewDataInputStream (Infromserver); System. out. println ("Server says"+inch. readUTF ()); Client.close (); } Catch(Exception ex) {ex.printstacktrace (); } }}
Java Basics-Network sockets (VI)