简体   繁体   English

Java套接字如何从两个不同的线程发送数据

[英]java socket how to send data from two different threads

I'm working on a socket based clientType1 - Server - clientType2 program. 我正在基于套接字的clientType1-Server-clientType2程序上工作。

clientType1 only sends data(actually a file) to the server, and the server relays the data to clientType2. clientType1仅将数据(实际上是一个文件)发送到服务器,服务器将数据中继到clientType2。

clientType1, and Type2 can be multiple. clientType1和Type2可以是多个。

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. 问题是,如果两个以上的clientType1尝试同时将文件发送到一个clientType2,则clientType2无法检索这两个文件中的一个。

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). 另一个方法是共享套接字,并从synchronized{}块访问它(我假设您了解Java中的同步原语)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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