以下是服务器代码
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 type ipconfig并将IPV4地址传递给这两种方法
问题是,当我的客户在通过wifi/lan连接的不同系统上时,他无法连接到我的服务器。
我将我的服务器绑定到我的路由器的连接地址,并将该地址提供给另一台机器上的客户机的IPV4 ()方法,但他得到"ConnectionTimedOutException“
客户端和服务器的端口参数相同,即8001
对于此测试,两个系统防火墙都处于禁用状态。
知道哪里出问题了吗?
发布于 2020-02-16 05:38:50
我不得不使用端口转发来解决我的问题
我采取了以下步骤
1)客户机使用我在ipv4 ()方法中从netwhatsmyip.com获得的globalnot本地连接地址
2)在我的服务器中,我使用来自ipconfig的本地ipv4地址调用bind()
3)我使用的公共端口是8001,我必须在路由器设置中为端口转发进行配置,以便它将来自我的全局ip:端口XXX.XXX:8001的所有数据包转发到我的本地ipv4地址:端口192.168.xxx.xxx:8001
这种方法有效,但效率不高,因为当我断开连接并重新连接时,我的IP地址会发生变化。如果有人知道不配置静态IP就能连接到服务器的更好的解决方案,请分享。谢谢你
https://stackoverflow.com/questions/60239456
复制