java套接字服务器和套接字客户端

时间:2016-11-09 20:59:25

标签: java sockets

我试图用java套接字做一个小例子。但我不能让它发挥作用。服务器正确接收客户端的请求。但问题来了,当我试图向服务器发送字符串“hello”。

在我调试时,服务器中的InputStream为null,因此它不会打印任何内容。我认为问题必须在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();
    }
}

提前致谢!

2 个答案:

答案 0 :(得分: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 :(得分:-1)

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

尝试将客户端更改为

 in = new BufferedReader (new InputStreamReader (sock. getInputStream ());