基于数据报通道的回声服务器
import java.net.InetSocketAddress; import java.net.SocketAddress; /* nowjava - 时代Java 提 供 */ import java.nio.ByteBuffer; import java.nio.channels.DatagramChannel; public class Main { public static void main(String[] args) throws Exception { DatagramChannel server = DatagramChannel.open(); InetSocketAddress sAddr = new InetSocketAddress("localhost", 5555); server.bind(sAddr); ByteBuffer buffer = ByteBuffer.allocate(1024); while (true) { System.out.println("Waiting for a message from" + " a remote host at " + sAddr); SocketAddress remoteAddr = server.receive(buffer); buffer.flip(); /* n o w j a v a . c o m 提供 */ int limits = buffer.limit(); byte bytes[] = new byte[limits]; buffer.get(bytes, 0, limits); String msg = new String(bytes);