Java UDP传输带回N

Java UDP transmission with Go back N

我有一个可以使用 UDP 传输文件的简单工作程序。但是对于每个客户端和服务器,我有两个套接字,它们在一个端口发送数据并在不同的端口接收数据。

例如,我的客户端socket_out在9000端口发送数据包,在9001端口监听socket_in接收数据。我的服务器socket_in在9000端口监听并发送ACK端口 9001 的数据包。

现在我想简化设计,在每个客户端和服务器上只使用一个端口号来接收和发送消息。比如客户端和服务端程序都在9000端口收发数据。

可以吗?我应该如何进行更改?我试图在同一个端口号上创建两个用于发送和接收的套接字,但我总是得到这个错误:

  java.net.BindException: Address already in use

我用谷歌搜索发现两个套接字不能共享同一个端口号。

添加代码: 发件人:

    public FileSender(String fileName, int unrelPort, String rcvFileName) {
    DatagramSocket socket_out_client, socket_in_client; 
    System.out.println("Start Sending " + fileName + " through port " +unrelPort + " as " + rcvFileName + ".");
    try {
        // create sockets
        socket_out_client = new DatagramSocket();
        socket_in_client = new DatagramSocket(unrelPort);

        // create input file

        File inputFile = new File(fileName);

        if (!inputFile.exists()) {
            System.err.println("Input file does not exist");
            System.exit(-1);
        }

        // create threads to process data
        InThread th_in = new InThread(socket_out_client,socket_in_client);
        OutThread th_out = new OutThread(socket_in_client, unrelPort, inputFile, rcvFileName);
        th_in.start();
        th_out.start();

    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

接收器相同

首先,当您可以使用相同的 socket_client 发送和接收时,为什么要在客户端创建两个用于发送和接收的套接字。您可以通过创建两个线程来实现这一点,一个用于发送,一个用于接收相同的 socket_client.

代码:类似这样

 DatagramSocket sock = new DatagramSocket();
 new Thread(new Runnable() {

                @Override
                public void run() {
   try{
     //create packet
     //your logic 
     sock.send(packet); 
    }
   }catch(Exception e){}

             }       
            }).start();
System.out.println("Debug :: "+"thread 1 started");

new Thread(new Runnable() {

                @Override
                public void run() {
   try{
        //your logic
        sock.receive(packet)
    }
   }catch(Exception e){}

             }       
            }).start();
System.out.println("Debug :: "+"thread 2 started"); 

端口号是嵌入在网络数据包中的数字。一旦计算机的操作系统处理了入站网络数据包,它需要 "know" 将数据包传递给哪个程序作为输入。端口号用于在接收操作系统的端口中查找程序以编程 table.

这就是为什么不能让两个程序从同一端口读取数据的原因,因为这会使操作系统无法确定应该将数据包发送到两个程序中的哪一个作为输入。

请注意,这不是导致端口冲突的唯一方法。你也可以在同一台机器上有两个程序副本 运行。