Skip to content

Instantly share code, notes, and snippets.

@Mr00Anderson
Created August 12, 2018 21:39
Show Gist options
  • Save Mr00Anderson/b40e496c356d94eeedfd69c32e53c40f to your computer and use it in GitHub Desktop.
Save Mr00Anderson/b40e496c356d94eeedfd69c32e53c40f to your computer and use it in GitHub Desktop.
package com.freeuniversegames.network.client;
import com.freeuniversegames.constants.Net;
import com.freeuniversegames.network.CachedEventLoopGroup;
import com.freeuniversegames.network.session.Session;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.InetSocketAddress;
public class UdpChannelFactory {
/**
* Simply a logger reference
*/
private static final Logger L = LoggerFactory.getLogger(UdpChannelFactory.class);
public static ChannelFuture getAndConnect(Session session,
CachedEventLoopGroup cachedEventLoopGroup,
Channel parentChannel,
int port){
ChannelFuture newChannelFuture = cachedEventLoopGroup.getNewChannelAndRegister(true, Net.Side.CLIENT);
L.trace("{} - Registering UDP channel {} to {}", session, newChannelFuture, cachedEventLoopGroup.getWorkerEventLoop());
if(newChannelFuture.isSuccess()){
L.trace("{} - Registering UDP channel {} to {} was a success. Channel Future {}", session, newChannelFuture, cachedEventLoopGroup.getWorkerEventLoop(), newChannelFuture);
Channel newChannel = newChannelFuture.channel();
InetSocketAddress remoteSocketAddress = (InetSocketAddress) parentChannel.remoteAddress();
InetAddress remoteInetAddress = remoteSocketAddress.getAddress();
InetSocketAddress udpRemoteSocketAddress = new InetSocketAddress(remoteInetAddress, port);
L.trace("{} - Configuring UDP channel and connecting remote address {}", session, udpRemoteSocketAddress);
ChannelFuture connectFuture = newChannel.connect(udpRemoteSocketAddress);
if(connectFuture.isSuccess()){
L.trace("{} - Connected UDP channel; remote address {}", session, udpRemoteSocketAddress);
parentChannel.closeFuture().addListeners((ChannelFutureListener) future -> {
newChannel.close();
L.debug("{} - the parent channel has closed; now closing this udp channel", session, parentChannel, newChannelFuture);
});
return connectFuture;
} else {
L.trace("{} - Failed connecting UDP channel; remote address {}", session, udpRemoteSocketAddress);
return connectFuture;
}
} else {
L.trace("{} - Registering UDP channel {} to {} failed. Channel Future {}", session, newChannelFuture, cachedEventLoopGroup.getWorkerEventLoop(), newChannelFuture);
return newChannelFuture;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment