我想用java套接字做一个小例子。但我无法让它工作。服务器正确接收客户请求。但问题来了,当我试图发送到服务器的字符串“你好”。java套接字服务器和套接字客户端之间的连接
正如我调试,服务器中的InputStream为空,所以它不会打印任何东西。我认为这个问题必须在PrinterWriter,也许我应该使用另一个类,我想与其他班级一样的BufferedWriter,但我不能使它工作
这里是我的代码
服务器
public class ServidorFechaHora {
static final int port = 5000;
static String line;
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ServerSocket ss = new ServerSocket(port);
while (true) {
/* accept nos devuelve el Socket conectado a un nuevo cliente.
Si no hay un nuevo cliente, se bloquea hasta que haya un
nuevo cliente.
*/
Socket soc = ss.accept();
System.out.println("Cliente conectado");
// Obtenemos el flujo de entrada del socket
InputStream is = (InputStream) soc.getInputStream();
//Función que llevaría a cabo el envío y recepción de los datos.
processClient(is);
}
}
private static void processClient(InputStream is) throws IOException {
// TODO Auto-generated method stub
BufferedReader bis = new BufferedReader(new InputStreamReader(is));
while ((line = bis.readLine()) != null){
System.out.println(line);
}
bis.close();
}
}
客户
public class ClienteFechaHora {
public static void main(String[] args) throws IOException, InterruptedException {
Socket client = null;
PrintWriter output = null;
//BufferedOutputStream out = null;
DateFormat hourdateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
try {
client = new Socket("127.0.0.1", port);
output = new PrintWriter(client.getOutputStream(), false);
while (true) {
System.out.println("Enviando datos...");
output.write("hello");
output.flush();
Thread.currentThread().sleep(2000);
//System.out.println("Fecha y hora: " + hourdateFormat);
}
}
catch (IOException e) {
System.out.println(e);
}
output.close();
client.close();
}
}
提前感谢!
我只是检查服务器以获取数据我虚拟客户端并且工作正常 –
服务器中的输入流永远不为空。不清楚你在问什么。 – EJP
EJP正如我所说的,我试图从客户端向服务器发送字符串“hello”,并将其显示在名为“processClient”的服务器方法中。我认为我很清楚,即使只是阅读说明或代码,我也会试着去做。请,下次更仔细阅读,而不是给我负面的观点。 :) – Javi