Java Sockets. Server-Client communication

后端 未结 3 639
孤城傲影
孤城傲影 2021-01-20 13:10

I am trying to connect a client with gui with a server withoout gui. Connection is being done, but i cant see any messages between these two apps. (i should get SERVER HERE

相关标签:
3条回答
  • 2021-01-20 13:19

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

    0 讨论(0)
  • 2021-01-20 13:25

    [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!

    0 讨论(0)
  • 2021-01-20 13:38

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

    0 讨论(0)
提交回复
热议问题