How to structure a threaded TCP client in Java
I need to write a threaded TCP client in Java but am unsure about how to best structure it. I would like the client to run on another thread so as to not block the main 开发者_运维问答thread.
Ideally I would create the client on the main thread and then instruct the client to connect to the server. The connecting which may take some time would happen on another thread. Once the client has connected, it would notify the main thread and start listening for incoming messages from the server. The main thread is notified as messages are received.
At the moment my plan is to have a TCP client class implement Runnable and perform both the connecting and receiving in the run method.
I'd appreciate any thoughts on how to structure the tcp client.
Some of the things which you should consider while structurinng Your application:
1. Ideally, there should be separate threads for reading and writing the network streams. Otherwise there may be problems.
2. If You want to "inform" other threads about something or pass something, consider the Java "Condition" idiom/object and/or the blocking Queues/Deques.
Take a look at JBoss Netty and handle the communication between the Threads with a Queue implementation that fits your needs.
Netty has a steer learning curve, but it pays of with a easy maintainable design and as long you dont need UDP transfer (then i would take a look at Apache Mina) it's just enough. Also you don't need to implement a State Machine with Netty.
精彩评论