我必须编写一个简单的 Java 聊天服务器,在其中存储对等 IP 地址的列表。当我发送消息时,我必须遍历每个地址并将其发送给每个对等方。这是我的代码:
import java.util.*;
import java.net.*;
import java.io.*;
class ChatServer{
static LinkedList<String> peerList;
static int port;
private final static int PACKETSIZE = 100;
public static void main(String args[]){
peerList = new LinkedList<String>();
peerList.add("127.0.0.1");
peerList.add("192.168.0.100");
try{
InetAddress inetAddress = InetAddress.getLocalHost();
port = Integer.parseInt(args[0]);
DatagramSocket clientSocket = new DatagramSocket(port, inetAddress);
BufferedReader br = (new BufferedReader(new InputStreamReader(System.in)));
String msg;
byte[] sendData = new byte[PACKETSIZE];
byte[] receiveData = new byte[PACKETSIZE];
while(true){
System.out.println("Enter your message: ");
msg = br.readLine() + "\r\n";
sendData = msg.getBytes();
itr = peerList.listIterator(0);
while (itr.hasNext()){
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, inetAddress.getByName(itr.next().toString()), port);
clientSocket.send(sendPacket);
}
DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length, inetAddress, port);
clientSocket.receive(receivePacket);
System.out.println("FROM:" + receivePacket.getAddress() + ":" + new String(receivePacket.getData()));
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
}
}
如您所见,我使用 localhost 和本地 IP 地址进行了尝试,并收到了消息:
"Cannot assign requested address: Datagram send failed".
我发现问题出在本地主机上,就好像我把它拿出来一样,消息会发送到我的本地地址。我已经检查并仔细检查了我的 etc/hosts 文件,并且 localhost 配置正确,即“ 127.0.0.1 localhost
”。控制台肯定是以管理员身份运行的。我也在禁用防火墙的情况下尝试了它,所以不是这样。
有谁知道这可能是什么原因造成的?