Created
May 3, 2017 17:52
-
-
Save mudlee/747770aca799f5fd79dfa8e25a20d25e to your computer and use it in GitHub Desktop.
Java & Vert.x UDP & TCP
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
tcpServer = vertx.createNetServer(new NetServerOptions().setPort(SERVER_PORT).setSsl(false).setHost(SERVER_HOST).setReuseAddress(true)); | |
tcpServer.connectHandler(socket -> { | |
LOGGER.debug("[TCP] connection from {}:{}", socket.remoteAddress().host(), socket.remoteAddress().port()); | |
socket.handler(buffer -> { | |
String data = new String(buffer.getBytes()); | |
LOGGER.debug("[TCP] data receiving from {}:{}, length is {}, data: {}", socket.remoteAddress().host(), socket.remoteAddress().port(), buffer.length(), data); | |
Optional<NetworkCommand> command = NetworkCommandParser.parse(data); | |
if (!command.isPresent()) { | |
return; | |
} | |
LOGGER.trace("[UDP] Command parsed: '{}'", command.toString()); | |
gameController.executeTCPNetworkCommand(command.get(), socket.remoteAddress()); | |
}); | |
socket.closeHandler(event -> LOGGER.debug("[TCP] connection closed {}:{}", socket.remoteAddress().host(), socket.remoteAddress().port())); | |
}); | |
tcpServer.listen(asyncResult -> { | |
if (asyncResult.succeeded()) { | |
LOGGER.debug("[TCP] Server is listening on {}:{}", SERVER_HOST, SERVER_PORT); | |
} else { | |
LOGGER.error("[TCP] Server listen failed on {}:{} - {}", SERVER_HOST, SERVER_PORT, asyncResult.cause()); | |
} | |
}); | |
udpSocket = vertx.createDatagramSocket(new DatagramSocketOptions().setIpV6(false).setReuseAddress(true)); | |
udpSocket.listen(SERVER_PORT, SERVER_HOST, asyncResult -> { | |
if (asyncResult.succeeded()) { | |
gameController.useSocket(udpSocket); | |
LOGGER.debug("[UDP] Server is listening on {}:{}", SERVER_HOST, SERVER_PORT); | |
udpSocket.handler(packet -> { | |
String commandData = packet.data().getString(0, packet.data().length()); | |
LOGGER.trace("[UDP] Command received from {}:{}, length: {}, data: {}", packet.sender().host(), packet.sender().port(), packet.data().length(), commandData); | |
Optional<NetworkCommand> command = NetworkCommandParser.parse(commandData); | |
if (!command.isPresent()) { | |
return; | |
} | |
LOGGER.trace("[UDP] Command parsed: '{}'", command.toString()); | |
gameController.executeUDPNetworkCommand(command.get(), packet.sender()); | |
}); | |
} else { | |
LOGGER.error("[UDP] Server listen failed on {}:{} - {}", SERVER_HOST, SERVER_PORT, asyncResult.cause()); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment