开发者

(New to threading) Best way to structure an instant messaging application?

开发者 https://www.devze.com 2023-02-15 02:54 出处:网络
I have been programming in Java for a while, but have never dealt with threa开发者_如何学运维ds before. In one of my classes, we learned about the easy-to-use yet vastly powerful Socket and ServerSock

I have been programming in Java for a while, but have never dealt with threa开发者_如何学运维ds before. In one of my classes, we learned about the easy-to-use yet vastly powerful Socket and ServerSocket classes. We made programs that could talk to each other through on the same machine (using "localhost"). There were two classes, a Server.java and a Client.java, but they could only talk to each other in a turn-based fashion.

I'd like to put the socket.accept() method on a new thread so the Server and Client programs can both send message while socket.accept() is waiting for new messages.

I have done well with threads so far, but I am unable to think of where to put the ServerSocket/Socket objects. If I put them in the thread that waits for incoming messages, I can't use that object for outgoing messages. If I put the ServerSocket/Socket objects in the Server.java/Client.java file directly, I can't (or I just don't know how) pass in the object to the thread, without creating a copy of it.

Any suggestions on how I should structure this program?

Thanks, Derek


I would say that the best way of running this application is as two separate processes/virtual machines, rather than two threads. Although you're running them on the same (virtual) machine at the moment, the whole point of instant messaging - and sockets - is to allow communication between different processes, which may be on different machines. You already have the two classes - simply make sure that both have main() methods so that they can run on their own.

Also, if you want full-duplex communication, you'd need to have two threads per process - one to wait for input from the user and send it to the other side, the other to wait for messages from the other side and present them to the user. Although you could set up a half-duplex system where a token is passed back and forwards on a single socket, you will likely find it much easier if you set up one incoming socket and one outgoing socket per end.

If you want to do full duplex communication from both ends, I don't think this is really a client/server relationship. If both sides are able to talk to each other equally, they're really more peers. By all means have a 'server' class that listens for incoming messages, and a 'client' class that sends outgoing ones, but have one of each on every machine. These map quite closely to the sending and receiving threads.

0

精彩评论

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

关注公众号