Java Socket Class with Examples: Establishing TCP Communication
Learn how to use the Java Socket class to enable communication between two computers via TCP. Explore how client and server programs create socket objects to establish a connection and exchange data by reading and writing to these sockets.
Java Socket Class with Examples
Sockets enable communication between two computers using TCP. A client program creates a socket to connect to a server.
Once the connection is established, the server creates its own socket object. The client and server can then communicate by writing to and reading from these sockets.
The java.net.Socket
class represents a socket, while the java.net.ServerSocket
class allows a server to listen for clients and establish connections.
Communication occurs via I/O streams, with each socket having both an OutputStream
and an InputStream
. The client's OutputStream
connects to the server's InputStream
, and vice versa.
Declaration
public class Socket
extends Object
implements Closeable
Constructors
Method & Description |
---|
public Socket() Creates an unconnected socket using the system-default type of SocketImpl . |
public Socket(String host, int port) throws UnknownHostException, IOException Attempts to connect to the specified server at the given port. |
public Socket(String host, int port, InetAddress localAddr, int localPort) throws IOException Creates a socket connected to the specified remote host and port, binding to the provided local address and port. |
public Socket(InetAddress host, int port) throws IOException Identical to the previous constructor but uses an InetAddress object for the host. |
public Socket(InetAddress host, int port, InetAddress localAddress, int localPort) throws IOException Similar to the previous constructor, using an InetAddress for the host. |
public Socket(Proxy proxy) Creates an unconnected socket, specifying the type of proxy to use. |
Methods
Method & Description |
---|
void bind(SocketAddress bindpoint) Binds the socket to a local address. |
void close() Closes this socket. |
void connect(SocketAddress endpoint) Connects this socket to the server. |
SocketChannel getChannel() Returns the unique SocketChannel object associated with this socket, if available. |
InputStream getInputStream() Returns an input stream for this socket. |
OutputStream getOutputStream() Returns an output stream for this socket. |
boolean isConnected() Checks if the socket is connected. |
String toString() Converts this socket to a String. |
Socket Client Example
The following GreetingClient
program connects to a server using a socket, sends a greeting, and waits for a response.
GreetingClient.java
package com.example;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class GreetingClient {
public static void main(String [] args) {
String serverName = args[0];
int port = Integer.parseInt(args[1]);
try {
System.out.println("Connecting to " + serverName + " on port " + port);
Socket client = new Socket(serverName, port);
System.out.println("Just connected to " + client.getRemoteSocketAddress());
OutputStream outToServer = client.getOutputStream();
DataOutputStream out = new DataOutputStream(outToServer);
out.writeUTF("Hello from " + client.getLocalSocketAddress());
InputStream inFromServer = client.getInputStream();
DataInputStream in = new DataInputStream(inFromServer);
System.out.println("Server says " + in.readUTF());
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
Connecting to localhost on port 6066
Just connected to localhost/127.0.0.1:6066
Server says Thank you for connecting to /127.0.0.1:6066
Goodbye!
Socket Server Example
The following GreetingServer
program listens for clients on a specified port.
GreetingServer.java
package com.example;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
public class GreetingServer extends Thread {
private ServerSocket serverSocket;
public GreetingServer(int port) throws IOException {
serverSocket = new ServerSocket(port);
serverSocket.setSoTimeout(10000);
}
public void run() {
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 = new DataInputStream(server.getInputStream());
System.out.println(in.readUTF());
DataOutputStream out = new DataOutputStream(server.getOutputStream());
out.writeUTF("Thank you for 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 void main(String [] args) {
int port = Integer.parseInt(args[0]);
try {
Thread t = new GreetingServer(port);
t.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Output
Waiting for client on port 6066...
Just connected to /127.0.0.1:49462
Hello from /127.0.0.1:49462
How to Compile and Run
To compile and run the client and server, use the following commands:
# Start the server
$ java GreetingServer 6066
# Start the client
$ java GreetingClient localhost 6066