2016-11-09 192 views
-1

我想用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(); 
    } 
} 

提前感谢!

+0

我只是检查服务器以获取数据我虚拟客户端并且工作正常 –

+0

服务器中的输入流永远不为空。不清楚你在问什么。 – EJP

+0

EJP正如我所说的,我试图从客户端向服务器发送字符串“hello”,并将其显示在名为“processClient”的服务器方法中。我认为我很清楚,即使只是阅读说明或代码,我也会试着去做。请,下次更仔细阅读,而不是给我负面的观点。 :) – Javi

回答

1

您的服务器从套接字读取行由行:

BufferedReader bis = new BufferedReader(new InputStreamReader(is)); 

while ((line = bis.readLine()) != null){ 
    System.out.println(line); 
} 

BufferedReader.readLine()如下记载:

读取一行文本。换行符被换行符('\ n'),回车符('\ r')或回车符后面的换行符中的任何一个结束。

所以它不会返回,直到它读取行结束符。

你,另一方面客户端刚写入字符串“Hello”没有行终止:

output.write("hello"); 
output.flush(); 

如果你想读的文本行中的服务器,你已经送线文本(包括行终止)在客户端:

output.write("hello\n"); 
output.flush(); 
-1

您的问题似乎是在为PrintWriter是“面向字符的”流,它扩展了Writer类。 并在服务器上尝试使用InputStream的,这是“面向字节”和扩展的InputStream

尝试将客户端更改为

in = new BufferedReader (new InputStreamReader (sock. getInputStream()); 
相关问题