Junior — Middle
Did you connect to the server during your last project?
sobes.tech AI
Answer from AI
Yes, in my recent Java project, I implemented server connection using sockets. For example, for a TCP connection, I used the Socket class from the standard library. Here's a simplified example:
import java.io.*;
import java.net.Socket;
public class Client {
public static void main(String[] args) {
try (Socket socket = new Socket("example.com", 80);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {
out.println("GET / HTTP/1.1\r\nHost: example.com\r\n\r\n");
String responseLine;
while ((responseLine = in.readLine()) != null) {
System.out.println(responseLine);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
This approach allows sending requests and receiving responses from the server over TCP.