Reputation: 4173
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.
Upvotes: 4
Views: 8914
Reputation: 310893
In addition to all the other comments, you shouldn't close the socket itself, you should close the outermost output stream you have created around the socket's output stream. That will:
(a) flush the output stream (b) close it (c) close the input stream, and (d) close the socket.
Upvotes: 2
Reputation: 99
//Put the line
output.flush();
//in the end of the TestServer.java
//and in the TestClient.java I have used the code as given below
Socket socket = new Socket("127.0.0.1", 1111);
BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
while((str=input.readLine())!=null){
System.out.println("Input: " + str);
}
socket.close();
}
Upvotes: 1
Reputation: 62439
input.readLine
expects a newline in the input string. Try to replace the output.write
with output.println
.
I just tested it now and it should work correctly like this.
Upvotes: 2
Reputation: 7381
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.
Upvotes: 6