这是服务器代码
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);}
}
这是客户代码
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)
{
}
}
您可以看到,出于项目特定目的,我的客户端和服务器都必须处于非阻止模式。
现在此代码何时生效
1)客户端和服务器都在同一台计算机上,并且客户端和服务器的IP参数均为“ localhost”
2)客户端和服务器都在同一台计算机上,并且客户端和服务器的IP参数都是我路由器的网络地址[我在Windows中,所以我进入cmd键入ipconfig并将IPV4地址传递到这两种方法中]
问题是当我的客户端位于通过wifi / lan连接的其他系统上时,我的客户端无法连接到服务器。
我将服务器绑定到路由器的IPV4地址,并将相同的地址提供给另一台计算机上我的客户端的connect()方法,但是他得到了“ ConnectionTimedOutException”
客户端和服务器的端口参数相同,均为8001
此测试均禁用了系统防火墙。
有什么问题的主意吗?
答案 0 :(得分:0)
我不得不使用端口转发来解决我的问题
我执行了以下步骤
1)客户端使用connect()方法中从网络[whatsmyip.com]获取的全局[非本地ipv4]地址
2)在服务器中,我使用本地ipv4地址(来自ipconfig)调用bind()
3)我使用的通用端口是8001,我必须在路由器设置中配置该端口以进行端口转发,因此它将所有数据包从全局ip:port XXX.XXX.XXX.XXX:8001转发到本地ipv4地址:端口192.168.xxx.xxx:8001
这种方法行得通,但效率不高,因为当我断开连接并重新连接时,我的IP发生了变化。如果有人知道在不配置静态IP的情况下连接服务器的更好解决方案,请共享。谢谢你