0

所以我有一个平板电脑,我想基本上把它做成一个 TCP(或 UDP)套接字服务器,这样多部手机就可以向它发送数据。我还希望能够将回复发送回手机。到目前为止我所拥有的不起作用...

服务器:

Log.i("Server", "Starting server...");
                try {
                    ServerSocket ss = new ServerSocket(8080);
                    Log.i("Server", "Server status: " + ss.isBound());
                    while(true){
                        //Server is waiting for client here, if needed
                        Socket s = ss.accept();
                        Log.i("Server", "Server is accepting connections: " + s.isConnected());
                        BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                        PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush
                        Log.i("Server", "Initialized input and output");
                        String st = input.readLine();
                        Log.i("Server", "From client: "+st);
                        output.println("Good bye and thanks for all the fish :)");
                    }

                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }

和客户(电话):

try {
                    Socket s = new Socket("192.168.0.106", 8080);

                    //outgoing stream redirect to socket
                    OutputStream out = s.getOutputStream();

                    PrintWriter output = new PrintWriter(out);
                    output.println("Hello Android!");
                    BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream()));
                    //read line(s)
                    String st = input.readLine();
                    tv.setText(st);
                    //Close connection
                    s.close();


                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
4

1 回答 1

1

您的客户可能没有刷新 println

尝试在构造函数中指定 autoflush

PrintWriter output = new PrintWriter(out, true);

或在打印下方手动添加冲洗

output.println("Hello Android!");
output.flush();
于 2012-05-31T04:28:49.740 回答