3

我有两个 Java 应用程序,其中一个 Android 客户端连接到计算机上的服务器并使用 BufferedWriter 通过 websockets 发送消息。

客户端:

    try {
        toast("Sending...");
        Socket sock = new Socket(ip, PORT);
        OutputStream os = sock.getOutputStream();
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
        bw.flush();
        bw.write("Hello Server!");
        toast("Connected!");
    } catch (UnknownHostException e) {
        toast(e.getMessage());
    } catch (IOException e) {
        toast(e.getMessage());
    }

服务器:

public static void main(String[] args) {
    ServerSocket server;
    ConnectionThread ct;
    Socket s;
    ExecutorService es = Executors.newSingleThreadExecutor();
    try {
        System.out.println("Starting server...");
        server = new ServerSocket(1337);
        s = server.accept();
        ct = new ConnectionThread(s);
        es.execute(ct);
    } catch (IOException ex) {
        ex.printStackTrace();
    }       
}

ConnectionThread班级:

public class ConnectionThread implements Runnable {
    private Socket sock;
    private InputStream is;
    private BufferedReader br;
    private boolean online;
    public ConnectionThread(Socket s) {
        System.out.println("Creating connection thread.");
        this.sock = s;
        online = true;
    }
    @Override
    public void run() {
        String input = "";
        try {
            System.out.println("Starting to read...");
            is = sock.getInputStream();
            br = new BufferedReader(new InputStreamReader(is));

            while (online) {
                input = br.readLine();
                if(input != null){
                    System.out.print("Received message: ");
                    System.out.println(input);
                }

            }

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

当我运行服务器,然后运行客户端时,客户端将显示“已连接!” toast,服务器的输出将是:

Starting server...
Creating connection thread.
Starting to read...

因此,似乎实际上正在建立连接,但消息没有到达。有谁知道为什么会发生这种情况?

4

3 回答 3

4

您的服务器需要一个由换行符终止的完整行。尝试:

bw.write("Hello Server!");
bw.newLine();
于 2012-10-16T14:54:09.240 回答
0

像这样做...

String s = new String();

while ((br.readLine())!=null) {

                s = s+br.readLine();

                    System.out.print("Received message: ");
                    System.out.println(input);
                }

            }

     bw.println("Hello Server");
于 2012-10-16T14:54:43.310 回答
0

我注意到您没有在客户端上发送结束行,因此 BufferedReader.readline() 将永远不会返回,因为它无法匹配 \n 字符。再试一次

        bw.write("Hello Server!\n");

在客户端。

于 2012-10-16T14:56:55.620 回答