Hello,
I have a webpage with one link to one
Servlet.
this Servlet is supposed to connect to one (working) server on port 4445.
I send one
string to the server and he invokes one method and respondes with another String.
The servlet correctly sends the string to the server the method on the server is working but the Servlet is not getting the response from the server. The server method for sending is well implemented.
The servlet is supposed to print HTML code after receiving something. I'm using TOMCAT7 as the servlet container.
Can you please help?
thank you very much!
THREAD ON THE SERVER:
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
String input = in.readLine();
if (input.equals("listar"))
{
System.out.println("RECEIVED"+input);
out.print(ServidorSubs.listaEcrasValues());
System.out.println("SENT"+ServidorSubs.listaEcrasV alues());
}
else
System.out.println("RECEIVED"+input);
in.close();
out.close();
socket.close();
}catch (IOException e){
e.printStackTrace();
}
}
SERVLET CODE:
/**
* envia para o servidor o pedido de listar
* o que este tem no HashMap de ecrãs
*/
import java.net.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ListarEcras extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// IP do servidor
String servidor = "127.0.0.1";
listar(servidor,4444);
}
public void listar (String servidor, int porta)
{
String ecras = null;
Socket socket = null;
PrintWriter out = null;
BufferedReader in = null;
try { //1.Open a socket.
socket = new Socket(servidor, porta);
//Open an output stream to the socket.
out = new PrintWriter(socket.getOutputStream(), true);
//Open an intput stream to the socket.
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
} catch (UnknownHostException e) {
System.err.println("Don't know about host: " +servidor);
System.exit(1);
} catch (IOException e) {
System.err.println("Não consigo criar o OutputStream para o :" +servidor);
System.exit(1);
}
//write to the stream
out.println("listar");
//WAIT FOR RESPONSE FROM SERVER
try{
ecras = in.readLine();
out.println("<html>");
out.println("<head>");
out.println("<title> " + ecras + "</title>");
out.println("</head>");
out.println("<body>");
out.println("
Hello World!
");
out.println("</body>");
out.println("</html>");
}catch (IOException e){
System.err.println("Erro: "+e.getMessage());
System.exit(1);
}
try{
//close stream
out.close();
in.close();
//close o socket
socket.close();
}catch (IOException e) {
System.err.println("Não consegui fechar os sockets");
System.exit(1);
}
}
}