Learn how to write TCP servers using Java's java.net package
TCP is a widely used network protocol. It's the underlying protocol for HTTP, SSH and many other protocols that you're probably familiar with.
In this concept, we'll learn how to write a TCP server in Java using the java.net package.
Not familiar with TCP? Try the “TCP: An Overview” concept first.
TCP is a widely used network protocol. It's the underlying protocol for HTTP, SSH and many other protocols that you're probably familiar with.
In this concept, we'll learn how to write a TCP server in Java using the java.net package.
Not familiar with TCP? Try the “TCP: An Overview” concept first.
java.net packageJava's java.net package provides access to networking primitives.
To write TCP servers in Java, you'll need to be familiar with the following:
java.net.Socketjava.net.ServerSocketjava.net.ServerSocket.acceptjava.net.Socket.getInputStream java.net.Socket.getOutputStreamjava.io.InputStream.readjava.io.OutputStream.writeWe'll start by looking at java.net.Socket and java.net.ServerSocket.
The java.net.Socket class can be used to initiate outbound connections.
Example usage:
// Connects to a TCP server running on localhost:8080
Socket socket = new Socket("localhost", 8080);
The java.net.ServerSocket class is used to create TCP servers that listen for incoming connections.
Example usage:
// Starts a TCP server listening on port 8080
ServerSocket serverSocket = new ServerSocket(8080);
java.net.ServerSocket classThis is the constructor signature for java.net.ServerSocket:
public ServerSocket(int port) throws IOException
To create a TCP server, you'd specify a port number:
// Starts a TCP server listening on port 8080
ServerSocket serverSocket = new ServerSocket(8080);
This binds the server to all available network interfaces on the machine.
Once you've created a server, you can use the java.net.ServerSocket.accept method to accept incoming connections.
The java.net.ServerSocket.accept method blocks execution and waits for an incoming connection.
Socket clientSocket = serverSocket.accept();
When a client connects, it returns a java.net.Socket object representing the connection.
This socket object can be used to read and write data to the connection.
To read data from a connection, you first need to get an input stream from the socket:
Socket clientSocket = serverSocket.accept();
InputStream inputStream = clientSocket.getInputStream();
Then you can read bytes from the stream using the java.io.InputStream.read method.
public int read(byte[] b) throws IOException
You need to create a buffer (a byte array) to store the data you're reading, and then pass it to the method:
byte[] buffer = new byte[1024];
int readBytesCount = inputStream.read(buffer);
The InputStream.read method returns the number of bytes read, or -1 if the end of the stream has been reached (meaning the client closed the connection).
To write data to a connection, you first need to get an output stream from the socket:
OutputStream outputStream = clientSocket.getOutputStream();
Then you can write bytes to the stream using the java.io.OutputStream.write method.
public void write(byte[] b) throws IOException
You need to pass in a byte array b containing the data you want to send:
String message = "Hello, client!";
outputStream.write(message.getBytes());
After writing, you should use the java.io.OutputStream.flush method to ensure all data is sent immediately:
outputStream.flush();
Without it, your data might sit in an internal buffer and not actually be sent to the client until later.
Now that you're familiar with the java.net package and its various classes and methods, let's see how to put them all together to create a simple TCP server that echoes a string:
import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
public class EchoServer {
public static void main(String[] args) throws Exception {
// Start a TCP server on port 8080
ServerSocket serverSocket = new ServerSocket(8080);
System.out.println("Server listening on port 8080");
// Block until we receive an incoming connection
Socket clientSocket = serverSocket.accept();
System.out.println("Accepted connection from " + clientSocket.getRemoteSocketAddress());
// Get input and output streams
InputStream inputStream = clientSocket.getInputStream();
OutputStream outputStream = clientSocket.getOutputStream();
// Read data
byte[] buffer = new byte[1024];
int readBytesCount = inputStream.read(buffer);
// Write the same data back
outputStream.write(Arrays.copyOf(buffer, readBytesCount));
outputStream.flush();
}
}
You've now learnt how to use classes and methods in the java.net package to build a TCP server.
A quick recap of what we've covered:
java.net.Socket: Initiates outbound connections to a TCP server, and represents connections on the server side.java.net.ServerSocket: Creates a TCP server that listens for incoming connections.java.net.ServerSocket.accept: Accepts an incoming connection and returns a socket.java.net.Socket.getInputStream: Returns an InputStream to read data from the connection.java.net.Socket.getOutputStream: Returns an OutputStream to write data to the connection.java.io.InputStream.read: Reads data from the connection.java.io.OutputStream.write: Writes data to the connection.The full documentation for the java.net package can be found in the Java API documentation.