我希望我的客戶端應用程序是能夠將連接到服務器應用程序。Java廣播:拋出BindException
問題是我的客戶端不知道服務器ip(在局域網內)。
所以我嘗試使用java對象MulticastSocket。幸運的是,Oracle有一個example of Broadcasting的頁面。
這裏我已經重新安排了它供我使用。
Server代碼:
long FIVE_SECONDS = 5000;
int port = 4445;
DatagramSocket socket = new DatagramSocket(port);
while (true) {
System.out.println("Server running...");
try {
// message for client
String dString = "Hello Client";
byte[] buf = dString.getBytes();
// send
InetAddress group = InetAddress.getByName("230.0.0.1");
DatagramPacket packet = new DatagramPacket(buf, buf.length, group, port);
socket.send(packet);
// sleep for a while
try {
Thread.sleep((long)(Math.random() * FIVE_SECONDS));
}
catch (InterruptedException e) {
System.err.println("Interrupted Exception");
}
} catch (IOException e) {
System.err.println("IOException");
}
}
客戶端代碼:
MulticastSocket socket = new MulticastSocket(4445);
InetAddress address = InetAddress.getByName("230.0.0.1");
socket.joinGroup(address);
// receive the message
byte[] buf = new byte[256];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
String received = new String(packet.getData(), 0, packet.getLength());
System.out.println("Received: " + received);
socket.leaveGroup(address);
socket.close();
當我Srver運行:沒有問題,但是當我嘗試運行的客戶端扔java.net.BindException: Address already in use
原因客戶端和服務器正在偵聽/發有關port 4445
的信息。
但是不是這樣嗎? 要彼此連接,他們必須具有相同的端口號,否則他們將永遠不會'遇見'。
我可以解決這個問題嗎?怎麼樣?
端口號是否正確?
這是一個正確的解決有關未知服務器IP的問題?
謝謝!
雖然我不能提出這個問題,但同一端口上的兩個偵聽器將無法工作。一個端口就像一個IO流,當有兩個編寫者/讀者時,就會發生不好的事情。這就是爲什麼拋出一個'BindException'來防止壞事發生的原因。 – WorldSEnder
@WorldSEnder:可能你說得對,但是在我的問題(和[這裏](https://docs.oracle.com/javase/tutorial/networking/datagrams/broadcasting.html))中鏈接到Oracle的例子中,他們使用相同的端口號... – xdola
你是否運行過他們的例子?如果否,您是否在同一臺計算機上使用您的客戶端和服務器?如果是,那麼我可以解釋這個問題,如果沒有我不知道 – WorldSEnder