#
Java Socket Client Example
The tutorial explains to you how to create a client which connect to a server through a socket. This article has an example as well.
A socket
is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent to.
a socket = protocol + hostname/IP (of the local machine) + port number
For instance, for an Oracle database it is common to have something like " server_hostname:1521 " as a socket.
In Java, the java.net package provides support for the two common network protocols: TCP & UDP.
When we use the TCP
(transfer control protocol) a connection must first be established between the pair of sockets
(client & server). While one of the sockets listens for a connection request (server), the other asks for
a connection (client). Once two sockets have been connected, they can be used to transmit data in both
(or either one of the) directions. Every TCP connection can be uniquely identified by its two endpoints.
The TCP is a stream communication protocol and is used for implementing network services (such as rlogin, telnet and FTP).
The UDP
(user datagram protocol) is a connectionless protocol. There is no guarantee that the datagrams you
have sent will be received in the same order by the receiving socket (it is not a stream communication protocol).
UDP is less complex than TCP and incurs fewer overheads. The UDP could be useful in some communications in
distributed environments.
Here is a Java example of client using the sockets and the Transfer Control Protocol (TCP):
package socket.java.client.example;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class SimpleJavaSocketClientExample {
public static void main(String args[]) throws IOException {
final String host = "localhost";
final int portNumber = 1887;
System.out.println("Creating socket to '" + host + "' on port " + portNumber);
while (true) {
Socket socket = new Socket(host, portNumber);
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Server says:" + br.readLine());
BufferedReader userInputBR = new BufferedReader(new InputStreamReader(System.in));
String userInput = userInputBR.readLine();
out.println(userInput);
System.out.println("Server respond is: " + br.readLine());
if ("quit".equalsIgnoreCase(userInput)) {
socket.close();
break;
}
}
}
}
First you have to export the project into a jar file and run it standalone.
The Java client will send requests to the server and receive responses from the server:
A connection is created and closed for each client request. In my example, the server will respond to a request at a time.