简体   繁体   中英

java socket how to send data from two different threads

I'm working on a socket based clientType1 - Server - clientType2 program.

clientType1 only sends data(actually a file) to the server, and the server relays the data to clientType2.

clientType1, and Type2 can be multiple.

The issue is, if more then two clientType1 tries to send files to one clientType2 at the same time, clientType2 fails to retreive either of those two files.

I guess I know why this happens. It's because two threads on the server tries to write to the same socket at the same time. How can I fix this?

By having a queue that client serving threads write to and another thread that reads off the queue and writes data to the socket (the queue would have to be thread safe). That is one of the simplest possible solutions.

Another one would be to make the socket shared and access it from synchronized{} block (I assume you know about synchronization primitives in java).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM