开发者

PrintWriter sends the first message only

开发者 https://www.devze.com 2023-03-31 19:04 出处:网络
I have seen a similar problem as mine but I still wasn\'t able to resolve this.I am trying to do a relay chat.I\'ve done all the flushing. I even tried autoflush(with println). But after the first mes

I have seen a similar problem as mine but I still wasn't able to resolve this.I am trying to do a relay chat. I've done all the flushing. I even tried autoflush(with println). But after the first message I sent to server, succeeding messages aren't sent anymore. I am not closing the printwriter. I checked the socket and yes, it's still connected, I printed the message to be sent, nothing seems to be wrong. Help would be very much appreciated.

here is a part of the client code:

public void initializeConnection(){
    try {
        host = InetAddress.getLocalHost();
        clientSocket = new Socket(host.getHostAddress(), port);
        outToServer = new PrintWriter(clientSocket.getOutputStream(),true);
        String message = outMsgArea.getText()+"Hello";
        outToServer.println(message);
        System.out.println(clientSocket.isConnected());
    }
    catch(IOException ioEx) {
        ioEx.printStackTrace();
    } 
}

public void actionPerformed(ActionEvent e)
{
    if(e.getSource()==quit){
        try {
            outToServer.close();
            clientSocket.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    else if(e.getSource()==button){ 
        if(outMsgArea.getText()!=null || !outMsgArea.getText().equals("")){
            /*try {
                outToServer = new PrintWriter(clientSocket.getOutputStream(), true);
            } catch (IOException e1) {
                // TODO Auto-generated catch block
                e1.printStackTr开发者_运维知识库ace();
            }*/
            String message = outMsgArea.getText()+"Hello";
            System.out.println(clientSocket.isConnected());
            outToServer.println(message);
            outToServer.flush();
            //outToServer.println(message);
            outMsgArea.setText("");
        }
    }
}

server:

        while(true) {
            try {
                Socket connectionSocket = servSocket.accept();
                Scanner inFromClient = new Scanner(connectionSocket.getInputStream());
                String clientSentence = inFromClient.nextLine();
                System.out.println(clientSentence);
            }
            catch(IOException ioEx) {
                ioEx.printStackTrace();
            }
        }
    }


I don't think

Socket connectionSocket = servSocket.accept();
Scanner inFromClient = new Scanner(connectionSocket.getInputStream());

should be inside the while loop.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号