I am trying to execute server and client code in Java for the client to send a String
, the server to process and return it and the client to receive.
The customer is always kept listening.
But after receiving String
it hangs.
Server class
// porta do servidor
int serverDoor = 4000;
// numero maximo de conexões que o servidor aceita
int maxConnections = 10;
// servidor socket
ServerSocket server = null;
// conexão socket
Socket connection = null;
// saida dos dados
OutputStream output = null;
// entrada dos dados
InputStream input = null;
try {
server = new ServerSocket(serverDoor, maxConnections);
while (true) {
System.out.println("Esperando cliente");
connection = server.accept();
// abrindo o stream de saida
output = connection.getOutputStream();
output.flush();
// abrindo o stream de entrada
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
// recebendo
String teste = bufferedReader.readLine();
output.write("Teste".getBytes());
output.flush();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (output != null) {
output.close();
}
if (input != null) {
input.close();
}
if (connection != null) {
connection.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Client Class
Socket client;
OutputStream output;
InputStream input;
// Step 1: Create a Socket to make connection
client = new Socket(InetAddress.getByName(url), porta);
//client.setSoTimeout(15000); // 5 segundos
// Step 2: Get the input and output streams
output = client.getOutputStream();
output.flush();
input = client.getInputStream();
// Step 3: Process connection
output.write(msg.getBytes());
output.flush();
// recebendo
System.out.println("Antes de receber cliente");
StringBuilder sb = new StringBuilder();
int temp;
while ((temp = input.read()) > -1)
sb.append((char) temp);
System.out.println("Depois de receber cliente");
// Step 4: Close connection
if (output != null)
output.close();
if (input != null)
input.close();
if (client != null)
client.close();
return sb.toString();
}
After the method of receiving the String it to, I use Windows 8, I do not know if this might represent something.