我正在尝试使用mutliple客户端
创建类似于客户端服务器聊天系统的东西服务器端代码
public class Server{
private Socket socket=null;
private ServerSocket serversocket=null;
public Server(int port){
Values val = new Values();
while(true){
try{
serversocket=new ServerSocket(port);
System.out.println("Server started\nWaiting for clients ...");
socket=serversocket.accept();
System.out.println("Client accepted");
ProcessRequest pRequest= new ProcessRequest(socket, val);
Thread t = new Thread(pRequest);
t.start();
}
catch(Exception e){
System.out.println("Socket creation exception: "+e);
break;
}
}
现在,当我在任何端口上运行服务器来侦听连接时,它会抛出异常
Server started
Waiting for clients ...
Client accepted
Socket creation exception: java.net.BindException: Address already in use (Bind failed)
但是我能够在客户端和服务器之间发送和接收消息而没有任何问题。
它显示错误,但线程正确启动并按原样处理请求。
那么,为什么会出现这种异常,以及如何修复它?
使用线程的类 -
class ProcessRequest implements Runnable{
private DataInputStream inp=null;
private DataOutputStream oup=null;
private Socket socket=null;
private Values val=null;
private String ip;
ProcessRequest(Socket s, Values v){
socket=s;
val=v;
ip=(((InetSocketAddress) socket.getRemoteSocketAddress()).getAddress()).toString().replace("/","");
}
public void run(){
try{
inp=new DataInputStream(socket.getInputStream());
oup=new DataOutputStream(socket.getOutputStream());
}
catch(Exception e){
System.out.println(e);
}
String line = "";
while (!line.equalsIgnoreCase("exit")){
try{
line = inp.readUTF();
// System.out.println(line);
String[] tokens=line.split(" ");
if(tokens[0].equalsIgnoreCase("put")){
val.setValue(ip, tokens[1], tokens[2]);
}
else if(tokens[0].equalsIgnoreCase("get")){
String value=val.getValue(ip, tokens[1]);
oup.writeUTF(value);
}
}
catch(IOException i){
System.out.println(i);
return;
}
}
try{
inp.close();
oup.close();
socket.close();
}
catch(IOException i){
System.out.println(i);
return;
}
}
答案 0 :(得分:4)
ServerSocket只需要创建一次(在这种情况下),并绑定到IP和端口。
您在这里所做的是创建多个ServerSockets并绑定到同一个IP和端口。创建不同的ServerSockets并绑定到同一组IP和端口组合显然会引发此异常。
因此,为了使其工作,请从循环中删除ServerSocket创建行。
public Server(int port){
Values val = new Values();
// Add your ServerSocket code here instead of the loop
serversocket = new ServerSocket(port);
System.out.println("Server started\nWaiting for clients ...");
while(true) {
try {
socket=serversocket.accept();
System.out.println("Client accepted");
ProcessRequest pRequest = new ProcessRequest(socket, val);
Thread t = new Thread(pRequest);
// And so on...
}