我有一个Java电子表格应用程序,它提供的功能之一(我开发的)是工作表共享。基本上,任何人都可以是客户端或服务器,因为该应用程序同时具有服务器和客户端代码。作为服务器的用户创建共享,指定IP,然后创建并激活共享(最佳情况场景),服务器在其IP和选定端口上侦听客户端。
对于自动发现,我通过UDP广播使用DatagramSockets,而'真实通信'是基于TCP的(在客户端已经连接之后)。
我已经有了这个代码来从服务器向客户端发送活动共享列表(它发送List
InetSocketAddress
)。
服务器:
public class BroadcastList implements Runnable {
private final int BROADCAST_PORT = 8888;
public BroadcastList() {
}
@Override
public void run() {
try {
ActiveShareList asl = new ActiveShareList();
List<InetSocketAddress> shareList = asl.getActiveShareList();
DatagramSocket broadcast = new DatagramSocket(BROADCAST_PORT);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(out);
outputStream.writeObject(shareList);
outputStream.close();
byte[] listData = out.toByteArray();
byte[] message = new byte[10];
DatagramPacket listPacket = new DatagramPacket(listData, listData.length);
DatagramPacket messagePacket = new DatagramPacket(message, message.length);
broadcast.receive(messagePacket);
broadcast.send(listPacket);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
客户:
public void getShareList() {
DatagramSocket socket;
try {
InetSocketAddress address = new InetSocketAddress("255.255.255.255", 8888);
socket = new DatagramSocket();
byte[] buffer = new byte[10];
List<InetSocketAddress> shareList = new ArrayList<InetSocketAddress>();
byte[] listData = new byte[65535];
DatagramPacket messagePacket = new DatagramPacket(buffer, buffer.length, address.getAddress(), address.getPort());
DatagramPacket listPacket = new DatagramPacket(listData, listData.length);
socket.send(messagePacket);
socket.receive(listPacket);
ObjectInputStream inputStream = new ObjectInputStream(new ByteArrayInputStream(listData));
try {
shareList = (List<InetSocketAddress>) inputStream.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(JoinShareAction.class.getName()).log(Level.SEVERE, null, ex);
}
}
问题出在客户端,它在这一行上给出了java.io.IOException: Can't assign requested address
错误:socket.send(messagePacket);
。
任何人都知道这是什么问题?