multithread client-server chat, using sockets

前端 未结 2 1348
离开以前
离开以前 2021-01-07 12:33

Server and client communicating with my own protocol which looks like XMPP. I should to realize chat application. So when one user write String it immedeatly should be sende

相关标签:
2条回答
  • 2021-01-07 13:08

    Try this,

    Do Not use BufferedReader() with PrintWriter..... PrintWriter is itself the Bridge between byte level socket data and character form.

    Eg:

    I am showing for a single client, use the while loop for n nos of clients

    ServerSocket s = new ServerSocket(4444);
    
    Socket incoming = s.accept();
    
    OutputStream output = s.getOutputStream();
    
    PrintWriter pw = new PrintWriter(output,true);
    

    System.out.println(pw.write(new Scanner(System.in).nextLine()));

    0 讨论(0)
  • 2021-01-07 13:16

    You will need to multi-thread both the client and server. The client will need one thread that listens for messages from the server and writes them to his/her screen and one thread that waits for his/her keyboard input and sends it to the server. Likewise for each connection to the server, it will need a thread waiting for input from the client and one thread sending output from other users to the client.

    The reason you don't see incoming messages until you press enter is because of the client while loop. It's commented out now, but it looks like your loop used to:
    - Read incoming messages from server
    - Read input from keyboard
    - Send input to server

    So you read whatever was available from the server, and then the client waits for more keyboard input before reading from the server again (in the next iteration).

    Another word of advice, from my understanding, creating JAXBContext can be an expensive operation. You don't need to recreate it every time you send a message. Consider initializing one in your server and client and then reusing it for each marshall/unmarshall.

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