6

我目前正在为一款名为 GTA 的游戏开发 Match Maker,问题是游戏服务器使用 7777 端口,我需要向世界开放此端口以允许玩家加入服务器,我不希望用户对其路由器进行任何更改。

注意:游戏服务器不是我的,我不能修改它的源代码,我只是启动它。

所以,我发现Cling可以处理端口转发,但我不能让它工作!

我正在使用的代码:

public static void openports() throws UnknownHostException {
    InetAddress i = InetAddress.getLocalHost();
    System.out.println(i.getHostAddress());

    UpnpService upnpServiceTCP = new UpnpServiceImpl(new PortMappingListener(new PortMapping(7777, i.getHostAddress(), PortMapping.Protocol.TCP)));
    upnpServiceTCP.getControlPoint().search(new STAllHeader());

    UpnpService upnpServiceUDP = new UpnpServiceImpl(new PortMappingListener(new PortMapping(7777, i.getHostAddress(), PortMapping.Protocol.UDP)));
    upnpServiceUDP.getControlPoint().search(new STAllHeader());
}

任何人都知道让它工作吗?

4

2 回答 2

7

您可以使用以下代码实现您的目标

private void doPortForwarding() {

        PortMapping[] desiredMapping = new PortMapping[2];
         desiredMapping[0] = new PortMapping(8123, InetAddress.getLocalHost().getHostAddress(),
                PortMapping.Protocol.TCP, " TCP POT Forwarding");

         desiredMapping[1] = new PortMapping(8123, InetAddress.getLocalHost().getHostAddress(),
                    PortMapping.Protocol.UDP, " UDP POT Forwarding");


         UpnpService upnpService = new UpnpServiceImpl();
         RegistryListener registryListener = new PortMappingListener(desiredMapping);
         upnpService.getRegistry().addListener(registryListener);

        upnpService.getControlPoint().search();

    }
于 2016-04-18T17:01:53.867 回答
4

当您想要这样的 portforwad 端口时,Cling 会遇到一些问题。您应该使用以下代码:

UpnpServiceImpl upnpService = null;
PortMapping[] arr = new PortMapping[2];

    arr[0] = new PortMapping(7777, InetAddress.getLocalHost().getHostAddress(), PortMapping.Protocol.TCP,"My Port Mapping1");       
    arr[1] = new PortMapping(7777, InetAddress.getLocalHost().getHostAddress(), PortMapping.Protocol.UDP,"My Port Mapping2");

    upnpService = new UpnpServiceImpl(new PortMappingListener(arr));            

    upnpService.getControlPoint().search();         

不要忘记打开路由器上的 UPnP。

当您的通信结束时,您应该像这样关闭它:

upnpService.shutdown();
于 2015-04-26T12:11:29.210 回答