且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

多线程客户端 - 服务器聊天,使用套接字

更新时间:2022-10-17 21:52:51

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.

相关阅读

技术问答最新文章