Here Is The server code
void bind(String ip,int port)
{
socket=ServerSocketChannel.open();
socket.configureBlocking(false);
socket.register(acceptChannel=Selector.open(),SelectionKey.OP_ACCEPT);//Since Non Blocking Create Selector
socket.bind(new InetSocketAddress(ip,port));//Binding To Specified IP,Port So clients can connect
accept=threadService.scheduleAtFixedRate(this,100,interval,TimeUnit.MILLISECONDS);
}
void run()//Just Loops And Checks For New Clients
{
try
{
if(acceptChannel.selectNow()==0){return;}
Set<SelectionKey> channels=acceptChannel.selectedKeys();
Iterator<SelectionKey> iterator=channels.iterator();
while(iterator.hasNext())
{
SelectionKey key=iterator.next();
ServerSocketChannel server=(ServerSocketChannel)key.channel();
SocketChannel client=server.accept();
client.configureBlocking(false);
//Do Stuff With Client
iterator.remove();
}
channels.clear();
}
catch(Exception ex){errors.newClientError(ex,mainSocket,client);}
}
And Here Is The Client Code
SocketChannel clientSocket;
void connect(String IP,int port)throws IOException
{
clientSocket=SocketChannel.open();
clientSocket.configureBlocking(false);
clientSocket.register(connectChannel,SelectionKey.OP_CONNECT);//Non Blocking So Loop to check for status
clientSocket.connect(new InetSocketAddress(IP,port));//Do Actual Connection Here
waiting=threadService.scheduleAtFixedRate(this,100,10,TimeUnit.MILLISECONDS);
}
public void run()//Loops and checks for successful connection
{
try
{
if(connectChannel.selectNow()==0){return;}
Set<SelectionKey> channels=connectChannel.selectedKeys();
Iterator<SelectionKey> iterator=channels.iterator();
while(iterator.hasNext())
{
SelectionKey client=iterator.next();
SocketChannel channel=(SocketChannel)client.channel();
if(channel.finishConnect())
{
client.cancel();
iterator.remove();
channels.clear();
//Yeah we are connected job done
return;
}
iterator.remove();
}
channels.clear();
}
catch(Exception ex)
{
}
}
As You Can See Both my client and server must be in non blocking mode for project specific purposes.
Now This Code Works When
1)Both client and server are in same computer and IP parameter of both client & server is "localhost"
2)Both client and server are in same computer and IP parameter of both client & server is my router's network address[Im in windows so I go to cmd type ipconfig and pass the IPV4 address into both these methods]
The problem is that My Client cannot connect to my server when he is on an different system connected over wifi/lan.
I Bind My Server To My Router's IPV4 Address And Give That same address to My Client's connect() method on an different machine but he gets "ConnectionTimedOutException"
The port parameter is same for both client & server which is 8001
Both the systems firewalls are disabled for this test.
Any idea on what's going wrong?