Created
March 30, 2017 13:00
-
-
Save liuzhengyang/f4ce661ef416d21228e06e40eff30497 to your computer and use it in GitHub Desktop.
UDP java server echo example
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
public class UDPServer { | |
public void start() { | |
try { | |
DatagramChannel datagramChannel = DatagramChannel.open(); | |
datagramChannel.bind(new InetSocketAddress(8089)); | |
while(true) { | |
ByteBuffer byteBuffer = ByteBuffer.allocate(1024); | |
SocketAddress receive = datagramChannel.receive(byteBuffer); | |
byteBuffer.flip(); | |
System.out.println("Receive " + byteBuffer.toString()); | |
ByteBuffer returnBuffer = ByteBuffer.allocate(1024); | |
while(byteBuffer.hasRemaining()) { | |
returnBuffer.put(byteBuffer.get()); | |
} | |
returnBuffer.flip(); | |
datagramChannel.send(returnBuffer, receive); | |
} | |
} catch (SocketException e) { | |
e.printStackTrace(); | |
} catch (IOException e) { | |
e.printStackTrace(); | |
} | |
} | |
public static void main(String[] args) { | |
new UDPServer().start(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment