【发布时间】:2015-03-06 03:15:45
【问题描述】:
我有一个简单的工作程序,可以使用 UDP 传输文件。但是对于每个客户端和服务器,我有两个套接字,它们在一个端口发送数据并在不同的端口接收数据。
比如我的客户端socket_out在9000端口发送数据包,用socket_in接收数据,socket_in在9001端口监听。我的服务器socket_in在9000端口监听,在9001端口发送ACK数据包。
现在我想简化设计,在每个客户端和服务器上只使用一个端口号来接收和发送消息。例如,客户端和服务器程序都在 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读写。
-
你能详细说明一下吗?