簡體   English   中英

為什么我的服務器PrintWriter.println()無法通過套接字發送其消息?

[英]Why does my server PrintWriter.println() fail to send its message over a socket?

我知道您要說的是“ use .flush()”。 我所做的是構建一個程序,該程序將根據客戶端發送的消息同步3台計算機。

這是我正在使用的算法:

  • 將所有客戶端計算機連接到1台服務器計算機
  • 每台客戶端計算機到達准備執行的位置(這是“同步”部分,因此它將“就緒”標志發送到服務器)
  • 一旦所有計算機都通過套接字發送了“就緒”標志,服務器將通過PrintWriter和客戶端計算機發回“執行”,它們將執行並完成該迭代
  • 客戶端執行完畢后,它將向服務器發送“重置”標志,服務器准備重新啟動(服務器不在乎這種情況會發生多少次)
  • 然后,每個客戶端繼續進行下一個迭代以執行相同的操作,獲得“就緒”,然后當所有客戶端都“就緒”時,服務器再次發送“執行”,這就是問題所在。 我的Printwriter.println("execute")應該已發送,但從未在任何客戶端計算機上收到。

重申一下,第一次執行此過程時,一切按預期進行,在第二次迭代中,即使執行了out.println("execute)行,“ execute”命令也不會發送給客戶端。 。

難道我做錯了什么? 我也嘗試過PrintStream並且PrintStream都遇到相同的問題。 我對BufferedReader處理是否錯誤? 在我的一生中,我無法理解為什么第一次一切都會按預期運行,但是在第二次之后卻再也沒有將“執行”發送到客戶端計算機。 任何幫助都感激不盡。

服務器嗅探:

服務器接受客戶端后調用StartServerResponseThread()

// Init the nuc client
public void NucClientInit(Socket s) {
    new Thread() {
        public void run() {
            try {
                socket = s;
                bufOut = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
                //out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                //        socket.getOutputStream(), "UTF-8")), true);
                brffReadIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
                // Start the reponse thread
                StartServerResponseThread();
                // Confirm connection to client
                ConfirmConnection();
            } catch (IOException ex) {
                Logger.Log("Nuc:NucClientInit:IOException:ex: " + ex);
            }
        }
    }.start();

}

// Sends connect and waits for reponse back from server
private void ConfirmConnection() {
    Logger.Log("Sending connect to: " + ip_address);
    try {
        bufOut.write("connect");
        bufOut.newLine();
        bufOut.flush();
    } catch (IOException ex) {
        Logger.Log("Nuc:ConfirmConnection():bufOut:ex " + ex);
    }
    Logger.Log("Sent connect: " + ip_address);
    while (!connected) {

    }
    Logger.Log(ip_address + " Client is successfully Connected!");
}

// Handles any message from server
private void HandleClientMessage(String message) {
    switch (message) {
        case "connect":
            // Flag connection to confirm client connected (see ConfirmConnection())
            connected = true;
            break;
        case "ready":
            Logger.Log("Nuc:" + ip_address + ":received:ready");
            // Nuc is ready for sync now
            SetNucIsReady(true);
            break;
        case "reset":
            // Nuc has finished test (probably interleave)
            SetNucIsReady(false);
            break;
        default:
            Logger.Log("UNHANDLED CLIENT RSPONSE!!");
    }
}

// Will always run in a separate thread waiting for any response
// from the server
private void StartServerResponseThread() {
    new Thread() {
        public void run() {
            try {
                while ((fromClient = brffReadIn.readLine()) != null) {
                    HandleClientMessage(fromClient);
                }
            } catch (IOException ex) {
                Logger.Log("Nuc:StartServerResponseThread():IOException:ex: " + ex);
            }
        } // Close run()
    }.start();
}

// This method is used to send the execute command to the Nuc machine tied
// to this object.
public void Execute() {

    try {
        bufOut.write("execute");
        bufOut.newLine();
        bufOut.flush();
        Logger.Log(("Class:Nuc:method:Execute:" + ip_address + " sent "
                + "execute command"));
    } catch (IOException ex) {
        Logger.Log("Nuc:Execute():IOException:ex: " + ex);
    }
}

客戶:

    // Tell Server ready to execute
static void SendReady(){

    try {
        bufOut.write("ready");
        bufOut.newLine();
        bufOut.flush();
    } catch (IOException ex) {
        log("KPI_Socket:SendReady():bufOut:ex " + ex);
    }   
    log("Sent to Server 'ready'");
}
// Wait until execute is received from server
static void WaitForExecute(){
    log("Waiting for execute command from server");
    while(!execute){

    }
    log("Execute received from Server!");
    execute = false;
}   
// Tell server nuc needs to reset its isReady boolean
static void SendServerReset(){
    try {
        bufOut.write("reset");
        bufOut.newLine();
        bufOut.flush();
    } catch (IOException ex) {
        log("KPI_Socket:SendServerReset():bufOut:ex " + ex);
    }   
    log("Sent to Server 'reset'");
}
// Inform user connection is good
static void HandleConnect(){
    connected = true;
    log("Client Now Connected To Server");
}
// Handles any response from the server
static void HandleServerResponse(String serverResponse){
    switch (serverResponse){
        case "connect":
            HandleConnect();
            break;
        case "execute":
            execute = true;
            HandleExecute();
        default:
            log("UHANDLED RSPONSE FROM SERVER!!")

    }
}
// Will always run in a separate thread waiting for any response
// from the server
static void StartServerResponseThread(){
    new Thread(){
        public void run(){
            while ((fromServer = brffReadIn.readLine()) != null) {
                log("Message from Server: '" + fromServer + "'");
                HandleServerResponse(fromServer);
            }
            log("StartServerResponseThread() CLOSED!!!!!!!!");
        } // Close run()
    }.start();
}
// Init all components, connect to server and start server response thread
static void ConnectToServer(String host, int port){
    hostname = host;
    portNumber = port;
    try {

        log("Attempting to connect to " + hostname + "\n");
        socket = new Socket(hostname, portNumber);
        log("Connected to " + hostname);

        bufOut = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        //out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
          //              socket.getOutputStream(), "UTF-8")), true);
        brffReadIn = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
        // Start the server response thread to run in background
        StartServerResponseThread();
        // Wait for response from server on connect message
        while(!connected){
            log("Waiting for greeting message from server");
            wait_for(1);
        }
        try {
            bufOut.write("connect");
            bufOut.newLine();
            bufOut.flush();
        } catch (IOException ex) {
            log("KPI_Socket:ConnectToServer():bufOut:ex " + ex);
        }
    } catch (UnknownHostException e) {
        log("KPI_Socket:ConnectToServer():UnknownHostException" + e);
    } catch (IOException e) {
        log("KPI_Socket:ConnectToServer():IOException: " + e);
    }
} // Close ConnectToServer();

我知道您會說“使用.flush()” ...

不,我不是。 我要說“不要使用PrintWriter ”。 它吞沒了異常。 使用BufferedWriterwrite()newline()flush() 這樣,如果有任何例外,您將看到它們。 使用PrintWriter不能。

暫無
暫無

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

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