How do you test code that uses sockets (TCP)?

Testing code that utilizes sockets (TCP) involves creating a server and client that can communicate over the network. This can be efficiently done by using tools or libraries designed for socket programming in Java. Below is a simple example illustrating how you can establish a TCP connection, send data from a client to a server, and receive a response.

// Server Code import java.io.*; import java.net.*; public class Server { public static void main(String[] args) { try (ServerSocket serverSocket = new ServerSocket(8080)) { System.out.println("Server is listening on port 8080"); Socket socket = serverSocket.accept(); System.out.println("Client connected"); InputStream input = socket.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(input)); String message = reader.readLine(); System.out.println("Message from client: " + message); PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); writer.println("Hello from server!"); socket.close(); } catch (IOException e) { e.printStackTrace(); } } } // Client Code import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { try (Socket socket = new Socket("localhost", 8080)) { PrintWriter writer = new PrintWriter(socket.getOutputStream(), true); writer.println("Hello from client!"); BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); String response = reader.readLine(); System.out.println("Response from server: " + response); } catch (IOException e) { e.printStackTrace(); } } }

Testing Sockets TCP Java Socket Programming Server Client