I've tried to test socket connection in Java, but failed. Here is my code (two simple applications, server and client):
public class TestServer {
public static void main(String args[]) throws IOException {
ServerSocket serverSocket = new ServerSocket(1111);
System.out.println("Server socket created");
Socket socket = serverSocket.accept();
System.out.println("Socket accepted");
PrintWriter output = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Output created");
output.write("Output string");
socket.close();
serverSocket.close();
}
}
public class TestClient {
public static void main(String args[]) throws IOException {
Socket socket = new Socket("127.0.0.1", 1111);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("Input: " + input.readLine());
socket.close();
}
}
Output is (after running a server and, after it, client):
Server socket created
Socket accepted
Output created
Input: null
I've no idea what's the problem and why client didn't receive string sent to it. I'd appreciate any help.
Usually when I use classes like PrintWriter or OutputStream I need to flush its contents to send the data through a socket or write it to a file.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With