簡體   English   中英

Android TCP客戶端/服務器未正確傳遞消息(僅首次接收)

[英]Android TCP Client/Server not passing messages properly (Only first received)

我創建了兩個android應用程序,一個客戶端和一個服務器,利用TCP跨設備進行通信。 在服務器上,我有以下代碼來偵聽TCP通信:

private class StartServer implements Runnable {     
    public void run() {
            getState(); // This just refreshes the server state
            try {
                serverSocket = new ServerSocket(5000);
                appendLog("Server successfully listening ["+getLocalIpAddress() + ":5000]"); //appendLog function just uses runOnUiThread() to update the log textview
            } catch (IOException e) {
                appendLog("Could not listen on port: 5000");
                //System.exit(-1);
            }
            BufferedReader in = null;
            BufferedWriter out = null;
            String input = null;


            try {
                clientSocket = serverSocket.accept(); 
                in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                out = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));

                while (serverState) { //variable set by our getState() function

                    input = in.readLine();
                    appendLog("Received: " + input);
                    this.gotMessage(out, input);
                }
                in.close();
                out.close();
            } catch (IOException e) {
                //appendLog(e.toString());
                appendLog("Accept failed: 5000");
                //System.exit(-1);
            }
    }

哪個調用此函數以實際解析收到的消息:

private void gotMessage(BufferedWriter output, String msg) {
        if (msg != null) {
            String sString = msg;
            int to_do = 0;


            if (msg.matches("^(?i)(exit|quit|close)$")) {
                appendLog("Exiting");
                sString = "Goodbye";
                to_do=1;
            } else if (msg.matches("^(?i)(launch|run|open)\\s(.+)")) {
                appendLog("Launching application");
                sString = "Launching application";
            } else if (msg.matches("^(?i)(turn off|server off|deactivate)$")) {
                appendLog("Turning off server due to remote command.");
                sString = "Turning off...";
                to_do=2;
            } else if (msg.matches("^(?i)(restart|reboot)$")) {
                appendLog("Resetting server");
                sString = "Rebooting now...";
                to_do=3;
            }


            try {
                output.write("S: " + sString);
                output.newLine();
                output.flush();
            } catch (IOException e) {
                appendLog("Cannot parse message");
            }


            switch(to_do) {
                case 0:
                    break;
                case 1:
                    System.exit(0);
                    break;
                case 2:
                    serverOff();
                    break;
                case 3:
                    serverOff();
                    serverOn();
                    break;
                default:
                    break;
            }
        }
    }
}

使用Thread t = new Thread(new StartServer()); t.start()啟動服務器的線程本身Thread t = new Thread(new StartServer()); t.start() Thread t = new Thread(new StartServer()); t.start() 據我所知,這很好。 我可以打開一個終端和telnet到IP和端口,並來回傳遞通信而不會出現錯誤。 但是,當我嘗試從下面的客戶端代碼執行相同操作時。 我只得到第一個信息,而我傳遞的其他任何信息都消失在空白中。

public void sendToServer(View v) {
    try {
        String ip = ((TextView)findViewById(R.id.ip_box)).getText().toString(); //User entered IP address
        String to_send = ((EditText)findViewById(R.id.send_to_server)).getText().toString(); //User entered text to send
        this.s = new Socket(ip, 5000);
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        appendLog("Sending: " + to_send);
        out.write(to_send);
                    out.newLine();
        out.close();
    } catch (Exception e) {
        Log.d("error", e.toString());
    }
}

您的to_send字符串中是否有行尾字符? 如果沒有,只需將out.newLine()添加到您的客戶端代碼中:

appendLog("Sending: " + to_send);
out.write(to_send);
out.newLine();

您的服務器代碼應如下所示,以支持多個客戶端:

// main server loop
while (serverIsActive) {
    clientSocket = serverSocket.accept(); 
    // spawn new thread for each client
    ClientThread ct = new ClientThread(clientSocket);
    ct.start();
}

ClientThread應該與客戶端套接字一起使用,並具有自己的讀取行循環。 一旦客戶端關閉套接字,它應該立即停止:

class ClientThread {
    ...
    public void run() {
        ....
        while ((inputLine = in.readLine()) != null) {
            // process client message
        }
        in.close();
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM