我已经建立了一个服务器/客户端,可以通过套接字进行通信。但是我在连接它们时遇到了一些麻烦。
首先我在端口7777(已打开)上启动我的服务器,然后启动我的客户端但得到java.net.BindException。我的编码错了吗?
服务器端:
public Server(int port) { // port = 7777
this.port = port; // dont bother with this line
try {
socket = new DatagramSocket(port);
} catch (SocketException ex) {
return;
}
run = new Thread(this, "Server");
run.start(); // starts thread to listen for sent client packets
}
客户方:
private boolean openConnection(String address, int port) { // returns boolean to check for established connection as well as establish it, port = 7777
try {
socket = new DatagramSocket(port); // THE ERROR IN OUTPUT POINTS TO THIS LINE
ip = InetAddress.getByName(address);
return true;
} catch (UnknownHostException | SocketException ex) {
ex.printStackTrace();
return false;
}
}
堆栈追踪:
java.net.BindException: Address already in use: Cannot bind
at java.net.DualStackPlainDatagramSocketImpl.socketBind(Native Method)
at java.net.DualStackPlainDatagramSocketImpl.bind0(DualStackPlainDatagramSocketImpl.java:81)
at java.net.AbstractPlainDatagramSocketImpl.bind(AbstractPlainDatagramSocketImpl.java:95)
at java.net.DatagramSocket.bind(DatagramSocket.java:376)
at java.net.DatagramSocket.<init>(DatagramSocket.java:231)
at java.net.DatagramSocket.<init>(DatagramSocket.java:284)
at java.net.DatagramSocket.<init>(DatagramSocket.java:256)
at chatprogram.client.Client.openConnection(Client.java:45)
at chatprogram.client.Client.<init>(Client.java:35)
at chatprogram.client.Login1$8.run(Login1.java:104)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:251)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:733)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:703)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)
CMD netstat -an output:
我没有10个代表:http://prntscr.com/4f1hmf和http://prntscr.com/4f1hs3
答案 0 :(得分:1)
不要在客户端创建DatagramSocket
。只需创建一个Socket
,它就不会在本地绑定到特定端口(就像服务器一样):
new Socket(address, port);
答案 1 :(得分:0)
抱歉浪费你的时间大家!
错误发生在客户端:
socket = new DatagramSocket(); // REMOVED THE PORT PARAMETER, works fine
如果我能在这里回复所有回复我的人,我愿意。但是再次感谢大家:)。
答案 2 :(得分:0)
您是否启用了Hyper V?
如果是:
Disable Hyper-V
使用以下命令保留端口
C:\WINDOWS\system32>netsh int ipv4 add excludedportrange protocol=tcp startport=49838 numberofports=1
最后:
Enable Hyper-V