欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

NIO基本(3)

程序员文章站 2022-07-13 17:00:24
...
DatagramChannel 是处理UDP协议

1. server
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

public class DatagramServer {
	public static void main(String[] args) throws Exception {
		DatagramChannel channel = DatagramChannel.open();
		channel.socket().bind(new InetSocketAddress(1234));

		ByteBuffer bf = ByteBuffer.allocate(1024);

		while (true) {
			System.out.println("listening  ... ");
			SocketAddress remoteAddress = channel.receive(bf);

			new DealClientThread(channel, remoteAddress, bf);
		}
	}
}

class DealClientThread implements Runnable {

	private DatagramChannel channel;
	private SocketAddress remoteAddress;
	private ByteBuffer bf;

	public DealClientThread(DatagramChannel channel,
			SocketAddress remoteAddress, ByteBuffer bf) {
		this.channel = channel;
		this.remoteAddress = remoteAddress;
		this.bf = bf;

		new Thread(this).start();
	}

	public void run() {
		try {
			// reveive
			bf.flip();
			String receivedString = Charset.forName("UTF-8").newDecoder()
					.decode(bf).toString();

			System.out.println("Receivet client " + remoteAddress.toString()
					+ " message: " + receivedString);

			// send
			String sendString = "Hi, client(" + remoteAddress.toString()
					+ ") I had receive your message.";
			ByteBuffer bfSend = ByteBuffer.wrap(sendString.getBytes("UTF-8"));
			channel.send(bfSend, remoteAddress);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}



2. client
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;
import java.util.Date;

public class DatagramClient {
	public static void main(String[] args) throws Exception {
		// send
		DatagramChannel channel = DatagramChannel.open();
		String sendString = "Hi, server. @" + new Date().toString();
		ByteBuffer sendBuffer = ByteBuffer.wrap(sendString.getBytes("UTF-8"));
		channel.send(sendBuffer, new InetSocketAddress("127.0.0.1", 1234));
		System.out.println("Send message to server end");

		// receive
		ByteBuffer receiveBuffer = ByteBuffer.allocate(80);
		SocketAddress remoteAddress = channel.receive(receiveBuffer);
		receiveBuffer.flip();

		String receivedString = Charset.forName("UTF-8").newDecoder()
				.decode(receiveBuffer).toString();
		System.out.println("Receive message from " + remoteAddress.toString()
				+ " server: " + receivedString);
	}
}
相关标签: UDP NIO