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();
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?