1 端口使用中 BindException : Address already in use: JVM_Bind
Exception in thread "main" java.lang.NullPointerException
at pack.CharServer.main(CharServer.java:25)
这是因为你在同一个端口8888启动两个服务端实例 。所以第二个在绑定8888的时候JVM抛出异常,告诉你这个端口已经占用。已经被一个JVM实例绑定了。
改的办法从这入手:ss = new ServerSocket(8888);
不要直接创建ServerSocket实例的时候就初始化端口。
先new ServerSocket();
然后判断 boolean isBound() 返回 ServerSocket 的绑定状态。
boolean isClosed() 返回ServerSocket 的关闭状态。
如果没有关闭并且没有绑定则执行:
void bind(SocketAddress endpoint, int backlog) 将 ServerSocket 绑定到特定地址(IP 地址和端口号)。 或者void bind(SocketAddress endpoint) 将 ServerSocket 绑定到特定地址(IP 地址和端口号)。
如果已关闭则重新new ServerSocket()
如果没有关闭而且已经绑定则什么也不做。
这样就不会出现第二次执行再绑定的错误。
参考java.net.ServerSocket的API很容易实现。上面的方法就是其中的。
package pack;
import java.io.*;
import java.net.*;
public class CharServer {
public void server() {
boolean started;
boolean choice;
DataInputStream dis = null;
ServerSocket ss = null;
Socket cs = null;
try {
if (null == ss) {
ss = new ServerSocket();
}
if (ss.isClosed()) {
ss = new ServerSocket();
}
if (!ss.isBound()) {
ss.bind(new InetSocketAddress(8888));
}
} catch (BindException be) {
System.out.println("端口使用中 BindException : " + be.getMessage());
} catch (IOException ioe) {
System.out.println("IOException : " + ioe.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
try {
started = true;
while (started) {
choice = false;
cs = ss.accept();
choice = true;
dis = new DataInputStream(cs.getInputStream());
System.out.println("a client connected!");
while (choice) {
String str = dis.readUTF();
System.out.println(str);
}
dis.close();
}
} catch (IOException e) {
System.out.println("connect exit ." + " IOException : "
+ e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
} finally {
try {
if (dis != null)
dis.close();
if (cs != null)
cs.close();
} catch (IOException e1) {
System.out.println("IOException : " + e1.getMessage());
}
}
}
public static void main(String[] args) {
new CharServer().server();
}
}
/**
* 开2个的时候为什么不会显示"端口正在使用中" 出现java.net.SocketException: Unrecognized Windows
* Sockets error: 0: JVM_Bind.这是什么错误..该怎么改..我不能追问.请回答仔细点
*/
改过的代码 你看看