Java Sockets. Server-Client communication

非 Y 不嫁゛ 提交于 2019-12-01 23:41:13

You're using readLine() which expects a newline character. either add a \n to the messages you are sending or don't use readLine().

[SOLVED] As TedTrippin and Alfie mentioned readline(), messed my code. After adding "\n" in each message, everything seems to work smooth! I also changed printwriter to bufferwritter in client code, and i also added a try-catch function in sendMessage, cause printwritter seems to cause some problem as well for some reason. Anyway, everything is set and done! Thanks guys!

UPDATED CLIENT CODE:

private void ClientRun() throws IOException{
    String message="CLIENT HERE! \n"; <----added \n here.
    sendMessage(message);
    do{
        try{
            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");
    }

public void sendMessage(String message){
    try{                                 <-----added try-catch statement
       output.write("CLIENT - "+message+"\n"); <----adding "\n" here is super userful, instead of having to add \n in each message.
        output.flush();
        showMessage(message);
    }catch(IOException ioException){
        System.out.println("\n ERROR!");
    }
}

protected BufferedReader input;
protected BufferedWriter output; <----changed printwriter to BufferWriter

UPDATED SERVER CODE:

public void ServerRunning() throws IOException{
    String message="SERVER HERE! \n";    <--- added \n here as well.
    sendMessage(message);
    do{
        try{

            message=input.readLine();
            showMessage("\n"+message);
        }catch(EOFException eofException){
                showMessage("\n Server ended the connection!");
    }

    }while(message!="EXIT");

}

Thanks guys!

After compairing this code with some I have written in the past using sockets , I noticed you are using output.write(string) and input.readline() - These do not mix well, readline() expects a newline and write does not give one.

Replace write() with println().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!