I'm looking for suggestions for non-blocking socket writes in Java. My code just needs to write some data out to a socket and completely forget about it. I don't care about the response or when the data is actually consumed. What's the best way to do this?
Best idea when you get into complexities like this is to use a networking library like KryoNet (more complex, more features) or PryoNet (less complex, less features) which both support simple asynchronous I/O over sockets. You can pick them apart to understand how they work, if you really want to. Note that a write on a Socket
only blocks if the send buffer is full.
If you don't take this route, to handle this simple case without thread synchronisation you need to use Selectors
and Channels
, as there's no way of easily ascertaining without a busy loop if a socket is 'writeable' at any point in time with no buffer fill level notification mechanism in the basic Socket
class. You could also use the socket in a thread, then it can block indefinitely without a problem, but then you may have some synchronisation issues.
Sounds to me like you're after asynchronous I/O. Here is a short example:
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
public class Test
{
public static void main(String[] args)
{
final AsynchronousSocketChannel out = AsynchronousSocketChannel.open();
out.connect(new InetSocketAddress("www.google.com", 80), null,
new CompletionHandler<Void, Void>()
{
@Override
public void completed(Void result, Void attachment)
{
ByteBuffer buffer = ByteBuffer.allocate(1024);
buffer.asCharBuffer().put("GET /index.html HTTP/1.1");
out.write(buffer, null, new CompletionHandler<Integer, Void>()
{
@Override
public void completed(Integer result, Void attachment)
{
// ignore the result
}
@Override
public void failed(Throwable t, Void attachment)
{
t.printStackTrace();
}
});
}
@Override
public void failed(Throwable t, Void attachment)
{
t.printStackTrace();
}
});
}
}
You don't need any fancy frameworks. Java7 asynchronous sockets are quite easy to use.
创建一个发布这些事件的线程,它将运行它的后台并将数据提交给服务器。
您可以使用Java NIO的选择器和通道(复杂) - 或者您可以尝试更友好的网络库,如Apache MINA ,它支持非阻塞I / O.
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.