【发布时间】:2018-02-11 10:48:35
【问题描述】:
我正在尝试制作类似于客户端服务器聊天系统的东西,具有多个客户端
服务器端代码
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;
}
}
【问题讨论】:
-
提示:总是打印异常的堆栈跟踪:它们准确地告诉问题是什么(异常的类型)以及它被抛出的位置。因此,您无需猜测会发生什么,只需阅读堆栈跟踪即可知道。另外,不要捕获异常。只捕获预期的异常,并且您可以正确处理。否则,让它们传播。
标签: java sockets network-programming client-server serversocket