java:读写操作上的单个套接字.全双工 [英] java: Single socket on read write operation. Full duplex

查看:161
本文介绍了java:读写操作上的单个套接字.全双工的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须实现使用特定源端口发送数据,并同时侦听该端口.全双工.有谁知道如何在Java上实现它.我试图创建用于侦听套接字输入流的单独线程,但是它不起作用.我无法将ServerSocket和客户端套接字绑定到相同的源端口,并且与netty相同. 呆板双工有什么解决方案吗?

I have to implement sending data with specific source port and in the same time listen to that port. Full duplex. Does anybody know how to implement it on java. I tried to create separate thread for listening on socket input stream but it doesnt work. I cannot bind ServerSocket and client socket to the same source port and the the same with netty. It there any solution for dull duplex?

    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());
        }
}
        }

推荐答案

我遇到了同样的问题,决定自己回答.我想与大家分享代码仓库.这确实很简单,您可以将其想法付诸实践.这是一个详尽的例子.这些步骤意外地看起来像Ordous的解决方案.

I had run into the same question and decided to answer it myself. I would like to share with you guys the code repo. It is really simple, you can get the idea to make your stuff work. It is an elaborate example. The steps accidentally look like Ordous's solution.

https://github.com/khanhhua/full-duplex-chat

随意克隆!这是我的周末作业.

Feel free to clone! It's my weekend homework.

这篇关于java:读写操作上的单个套接字.全双工的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆