DatagramChannel 举例

Server 端:

package datagram;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.charset.Charset;

public class UDPServer {

    private int port = 8008;
    private DatagramChannel channel;
    private int MAX_SIZE = 1024;
    
    
    
    
    public UDPServer(int port, int size) throws IOException {
        
        this.port = port;
        this.MAX_SIZE = size;

        channel = DatagramChannel.open();
        SocketAddress localAddr = new InetSocketAddress(this.port);
        channel.bind(localAddr);
        System.out.println("Server Starting...");
        
    }
    
    
    public UDPServer() throws IOException {
        
        this(8008, 1024);
    }
    
    
    public String echo(String msg) {
        
        return "echo:" + msg;
    }
    
    
    public void service() {
        
        ByteBuffer receiveBuffer = ByteBuffer.allocate(MAX_SIZE);
        while(true) {
            try {
                receiveBuffer.clear();
                InetSocketAddress client = (InetSocketAddress) channel.receive(receiveBuffer);
                receiveBuffer.flip();
                String msg = Charset.forName("GBK").decode(receiveBuffer).toString();
                System.out.println(client.getAddress().getHostAddress() + ":" + client.getPort() + " > " + msg);
                
                channel.send(ByteBuffer.wrap(echo(msg).getBytes()), client);
                
                if(msg.startsWith("bye"))
                    break;
                
            }
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    
    public static void main(String[] args) throws IOException {
        
        new UDPServer().service();
    }
}

 

 

Client 端:

package datagram;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.DatagramChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.Set;


public class UDPClient {

    private DatagramChannel datagramChannel = null;
    private ByteBuffer sendBuffer = ByteBuffer.allocate(1024);
    private ByteBuffer receiveBuffer = ByteBuffer.allocate(1024);
    private Charset charset = Charset.forName("GBK");
    private Selector selector;
    
    
    public UDPClient(int port) throws IOException {
        
        datagramChannel = DatagramChannel.open();
        InetAddress ia = InetAddress.getByName("10.11.3.220");
        InetSocketAddress isa = new InetSocketAddress(ia, port);
        datagramChannel.configureBlocking(false);
        datagramChannel.bind(isa);
        
        ia = InetAddress.getByName("10.11.3.160");
        isa = new InetSocketAddress(ia, 8008);
        datagramChannel.connect(isa);
        selector = Selector.open();
    }
    
    
    public UDPClient() throws IOException {
        
        this(7000);
    }
    
    
    public static void main(String[] args) throws IOException {
        
        int port = 7000;
        if(args.length > 0)
            port = Integer.parseInt(args[0]);
        
        final UDPClient client = new UDPClient(port);
        Thread receiver = new Thread() {
            public void run() {
                client.receiveFromUser();
            }
        };
        
        receiver.start();
        client.talk();
    }
    
    
    public void receiveFromUser() {
        
        try {
            BufferedReader localReader = new BufferedReader(new InputStreamReader(System.in));
            String msg = null;
            while((msg = localReader.readLine()) != null) {
                synchronized(sendBuffer) {
                    sendBuffer.put(encode(msg + "\r\n"));
                }
                if(msg.equals("bye")) 
                    break;
             }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    
    public void talk() throws IOException {
        
        datagramChannel.register(selector, SelectionKey.OP_READ|SelectionKey.OP_WRITE);
        while(selector.select() > 0) {
            Set<SelectionKey> readyKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = readyKeys.iterator();
            while(it.hasNext()) {
                SelectionKey key = null;
                try {
                    key = it.next();
                    it.remove();
                    
                    if(key.isReadable()) {
                        receive(key);
                    }
                    
                    if(key.isWritable()) {
                        send(key);
                    }
                }
                catch (IOException e) {
                    e.printStackTrace();
                    try {
                        if(key != null) {
                            key.cancel();
                            key.channel().close();
                        }
                    }
                    catch(Exception ex) {
                        ex.printStackTrace();
                    }
                }
            }
        }
    }
    
    
    public void send(SelectionKey key) throws IOException {
        
        DatagramChannel datagramChannel = (DatagramChannel) key.channel();
        synchronized(sendBuffer) {
            sendBuffer.flip();
            datagramChannel.write(sendBuffer);
            sendBuffer.compact();
        }
    }
    
    
    public void receive(SelectionKey key) throws IOException {
        
        DatagramChannel datagramChannel = (DatagramChannel) key.channel();
        datagramChannel.read(receiveBuffer);
        receiveBuffer.flip();
        
        String receiveData = decode(receiveBuffer);
        if(receiveData.indexOf("\n") == -1)
            return;
        
        String outputData = receiveData.substring(0, receiveData.indexOf("\n")+1);
        System.out.println(outputData);
        
        if(outputData.equals("echo:bye\r\n")) {
            key.cancel();
            datagramChannel.close();
            System.out.println("Closed connection with Server");
            selector.close();
            System.exit(0);
        }
        
        ByteBuffer temp = encode(outputData);
        receiveBuffer.position(temp.limit());
        receiveBuffer.compact();
    }
    
    
    public String decode(ByteBuffer buffer) {
        
        CharBuffer charBuffer = charset.decode(buffer);
        return charBuffer.toString();
    }
    
    
    public ByteBuffer encode(String str) {
        
        return charset.encode(str);
    }
}

 

posted on 2014-11-28 16:23  starzou  阅读(334)  评论(0编辑  收藏  举报

导航