I'm trying to make something similar to a client server chat system, with mutliple clients
Server side code
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;
}
}
Now when i run the server on any port to listen for connections, it is throwing exception
Server started
Waiting for clients ...
Client accepted
Socket creation exception: java.net.BindException: Address already in use (Bind failed)
But i'm able to send and receive message between the client and server without any problem.
It's showing the error but the thread starts correctly and processes the request as it should.
So, why is this exception occuring, and how to fix the same?
Class using the thread --
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;
}
}