Question

I have two designs for an instant message program that I'm writting in Java

The first idea uses 2 separate threads. The first thread overlooks the gui and sends out the instant message data through writing to a blocking socket. The 2nd thread uses another blocking socket to monitor for incoming packets from the friend. I'm not certain if using threads is the best way to approach this problem, but I find it to be easier to deal with than using non-blocking socketchannels.

The 2nd design that I have is to use non-blocking socket channels in one thread which will occasionally check to see if there is incoming or outgoing data. The nice thing about this design is that I don't have to worry about resource sharing among threads, but I'm not sure if its more efficient.

Honestly, all I really care about is making a program that runs smoothly and efficiently. What do you think would be a more efficient and easier design to build? I'm just playing around so I have no experience in building efficient and powerful client/server programs other than what my senses tell me.

Was it helpful?

Solution

Long time ago I made a software, which had the chat module with TCP/IP : sockets.

At the beginning for each client it was 2 Thread: the ReaderThread and the WriterThread. It wasn't enough, because the clients get disconnected. I needed to make an InactivityChecker thread too, because the reader wasn't able to detect disconnections at server side, and the writer only when he had message. 3 thread / client is a bit waste of the resources, but it can go up to 5000 simultaneous clients!! -it will eat your processors with context switching! Also has must take care of the maximum port numbers opened.

If you would like to allow more than 65525/2 clients "simultaneously" for technical reasons the asynchron way is the only was to go.

OTHER TIPS

You are writing a chat program, don't you? In this case, the amount of data sent ad received is so small that you should not care about efficiency. Do it the way which is easier to program. I would chose to send data directly in the UI thread (write latency should not be large) and read data in a separate thread, which then sends received data to the UI thread using well-known methods. In both directions, using plain blocking socket is the simpliest approach.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top