我必须实现使用特定源端口发送数据,同时监听该端口。全双工。有谁知道如何在java上实现它。我尝试创建单独的线程来侦听套接字输入流,但它不起作用。我无法将 ServerSocket 和客户端套接字绑定到相同的源端口,并且与 netty 相同。
双工无光泽有什么解决办法吗?
init(){
socket = new Socket(InetAddress.getByName(Target.getHost()), Target.getPort(), InetAddress.getByName("localhost"), 250);
in = new DataInputStream(socket.getInputStream());
out = new DataOutputStream(socket.getOutputStream());
}
private static void writeAndFlush(OutputStream out, byte[] b) throws IOException {
out.write(b);
out.flush();
}
public class MessageReader implements Runnable {
@Override
public void run() {
//this method throw exception EOF
read(in);
}
private void read(DataInputStream in){
while (isConnectionAlive()) {
StringBuffer strBuf = new StringBuffer();
byte[] b = new byte[1000];
while ((b[0] = bufferedInputStream.read(b)) != 3) {
strBuf.append(new String(b));
}
log.debug(strBuf.toString());
}
}
}
你想做的事情很奇怪:AServerSocket
是一个完全实现的套接字,它接受连接,它处理自己的消息,并且您绝对不能在其之上搭载另一个套接字。
使用 NIO 实现全双工相当简单:
- 创建一个
Channel
为您Socket
在非阻塞模式下
- 添加对兴趣 OP 的读取
- 和一个人一起睡觉
Selector
's select()
method
- 读取任何可读字节,写入任何可写字节
- 如果写入完成,则从感兴趣的 OP 中删除写入
- GOTO 3.
- 如果需要写入,请将字节添加到缓冲区,将写入添加到感兴趣的操作并唤醒选择器。 (稍微简化了,但我相信您可以在 Javadoc 中找到自己的方法)
这样,每次有空间时,您将完全加载传出缓冲区,并同时从传入缓冲区读取(好吧,单线程,但您不必完成写入即可开始读取等)。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)