首页 > 解决方案 > 套接字在while循环中不发送数据

问题描述

我正在尝试进行简单的网络通信,其中客户端将用户输入字符串发送到服务器,然后服务器显示到控制台。当我只发送一个字符串时,它工作正常,但是一旦我包装我的用户输入代码并在 while 循环中发送代码,服务器就什么也没有收到。

服务器 :

        ServerSocket serverSocket = null;
        try {
            serverSocket = new ServerSocket(PORT);
            System.out.println("Server now hosted on port " + PORT);
            Socket s = serverSocket.accept();
            System.out.println("A client has connected !");

            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());

            while(true){            
                //RECEIVE
                int data;
                String inString = "";
                while((data=bis.read()) != -1){
                    inString += (char)data;
                }
                System.out.println("SLAVE : " + inString);              
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            System.out.println("Port déjà utilisé");
        }finally {
            try {
                serverSocket.close();
                System.out.println("Server closed");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("Could not close port " + PORT);
            }
        }

客户 :

Scanner sc = new Scanner(System.in);
        Socket s = null;

        try {
            s = new Socket("127.0.0.1", PORT);

            BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
            BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());

            System.out.println("Connexion established !");
            while(true){ // without this while loop, it works fine
                String send = "";
                System.out.print(">> ");
                send = sc.nextLine();
                bos.write(send.getBytes());
                bos.flush();
            }

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("Could not connect");;
        }
        finally {
            try {
                s.close();
                System.out.println("Closing socket");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("Could not close connection");;
            }
        }
        System.out.println("End of client");
    }

我希望服务器在它即将到来时写入它从套接字读取的任何数据。但它什么也不做。我不确定问题是来自服务器还是客户端。

标签: javasocketsnetworking

解决方案


问题出在您的while((data=bis.read()) != -1){代码上。

它一直在循环,直到收到 EOS-1

当您没有客户端循环时,您的 Stream 将关闭,允许-1发送,但当您有循环时则不会。尝试使用服务器循环打印,如下所示

while((data=bis.read()) != -1){
   inString += (char)data;

   if (((char)data) == '\n') {
       System.out.println("SLAVE : " + inString);   
       inString = "";
   }
}

推荐阅读