I am trying to learn sockets using Java, and I successfully sent data to a ServerSocket running on my own machine. When I try to read from this socket using readline (so that I can simply respond to my sent message), my program freezes and will not return.
Here is the code:
public static void main(String[] args) throws UnknownHostException, IOException {
TCPClient cli = new TCPClient("127.0.0.1", "15000");
try {
cli.ostream.writeUTF("Teste");
String echo = cli.istream.readLine();
System.out.println(echo);
}
TCPClient is the class I defined, so I can test my program on a simpler interface before using swing in my homework. here is the code:
public class TCPClient {
public DataOutputStream ostream = null;
public BufferedReader istream = null;
public TCPClient(String host, String port) throws UnknownHostException {
InetAddress ip = InetAddress.getByName(host);
try {
Socket socket = new Socket(host, Integer.parseInt(port));
ostream = new DataOutputStream(socket.getOutputStream());
istream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (IOException ex) {
Logger.getLogger(TCPClient.class.getName()).log(Level.SEVERE, null, ex);
}
}
My server is pretty simple. After establishing a connection, he enters this loop and remains here until I close the client (due to an infinite loop). Subsequently, the exception handling returns it to the point before the start of the connection.
while(true){
String msg = istream.readLine();
System.out.println("Arrived on server: " + msg);
ostream.writeUTF("ACK: " + msg);
ostream.flush();
}
I don’t see what I am missing.
PS: wierd - , , , (, ), , . - concurrency, ?