为什么我的服务器PrintWriter.println()无法通过套接字发送消息?

时间:2015-08-13 02:13:18

标签: java multithreading sockets networking

我知道你要说什么"使用.flush()" ....我是。我所做的是构建一个程序,根据客户端发送的消息同步3台机器。

以下是我使用的算法:

  • 将所有客户端计算机连接到1台服务器计算机
  • 每台客户端计算机都已准备好执行(这是&#34;同步&#34;部分&#34;因此它向服务器发送&#34; ready&#34;标志)< / LI>
  • 一旦所有机器都发送了&#34; ready&#34;通过套接字标志,服务器发回&#34;执行&#34;通过PrintWriter和客户端机器,他们执行并完成该迭代
  • 客户端完成执行后,发送&#34; reset&#34;标志回服务器,服务器准备好全面启动(服务器不关心这将发生多少次)
  • 然后每个客户端继续进行下一次迭代以完成同样的事情,获得​​&#34;准备就绪&#34;,然后当所有客户都准备好&#34;时,服务器发送&#34;执行& #34;再次&lt; - 这就是问题所在。我的Printwriter.println("execute")应该已发送,但绝不会在任何客户端计算机上收到。

重申并明确,第一次执行此过程,一切都按预期进行,在第二次迭代中,&#34;执行&#34;命令永远不会发送到客户端,即使它执行out.println("execute)行。

我做错了吗?我也试过PrintStream并且一直看到同样的问题。我处理BufferedReader错了吗?对于我的生活,我无法理解为什么一切都是第一次按预期工作,但在第二次之后#34;执行&#34;永远不会发送到客户端计算机。任何帮助都感激不尽。

服务器片段:

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();

1 个答案:

答案 0 :(得分:1)

  

我知道你要说什么&#34;使用.flush()&#34; ...

不,我不是。我要说'不要使用PrintWriter&#39;。它吞没了例外。使用BufferedWriterwrite()newline()flush()。这样,如果有任何例外,你会看到它们。使用PrintWriter,您可以