在一台机器上运行服务器和客户端(netbeans 8.1)
问题描述:
我在运行一台(mac)机器上的服务器和客户端时遇到问题。我可以运行服务器,但是当我运行客户端时,它给了我一个错误java.net.BindException: Address already in use at java.net.PlainDatagramSocketImpl.bind0(Native Method)
据我所知,有一些需要使用的ssh调用ssh,但我不知道如何使用它来解决这个问题。 感谢在一台机器上运行服务器和客户端(netbeans 8.1)
public class WRRCourseWork {
public static void main(String[] args) {
try {
DatagramSocket IN_socket = new DatagramSocket(3000);
DatagramSocket OUT_socket = new DatagramSocket(5000);
IN_socket.setSoTimeout(0);
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
while (true) {
//recive the message
IN_socket.receive(packet);
String message = new String(buffer);
System.out.println("Got message: " + message.trim());
// send the message
String host = "";
InetAddress addr = InetAddress.getByName(host);
DatagramPacket OUT_Packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 5000);
OUT_socket.send(OUT_Packet);
System.out.println("Sending Message: "+ message.trim());
}
} catch (Exception error) {
error.printStackTrace();
}
}
...客户
public class Messages {
public static void main(String [] args) {
System.out.println("hiiiiiii");
//String host = "localhost";
try {
while (true) {
InetAddress addr = InetAddress.getLocalHost();
String message = "Hello World";
DatagramPacket packet = new DatagramPacket(message.getBytes(), message.getBytes().length, addr, 4000);
DatagramSocket socket = new DatagramSocket(4000);
socket.send(packet);
//socket.close();
}
} catch(Exception error) {
// catch all errors
error.printStackTrace();
}
}
}
答
你的服务器监听3000端口,从而改变你的客户在还使用3000端口,并只指定端口3000次,在包定义不插座。然后
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class Messages {
public static void main(String [] args) {
System.out.println("hiiiiiii");
//String host = "localhost";
DatagramSocket socket = null;
try {
while (true) {
InetAddress addr = InetAddress.getLocalHost();
String message = "Hello World";
DatagramPacket packet =
new DatagramPacket(message.getBytes(),
message.getBytes().length, addr, 3000);
socket = new DatagramSocket();
socket.send(packet);
socket.close();
}
} catch(Exception error) {
// catch all errors
error.printStackTrace();
}
}
}
在服务器上的结果应该是:
Got message: Hello World
Sending Message: Hello World
Got message: Hello World
Sending Message: Hello World
Got message: Hello World
Sending Message: Hello World
. . .