Java TCP异步数据接收

以前一直采用.Net编写服务端程序,最近须要切换到Linux平台下,因而尝试采用Java编写数据服务器。TCP异步链接在C#中很容易实现,网上也有不少可供参考的代码。但Java异步TCP的参考资料较少,网上例程可能是阻塞多线程方法,因为线程的开销较大,当客户端较多时系统资源的消耗也较大。java

综合网上和书本的相关知识,本文给出一个Java TCP异步接收数据的代码示例,并给出相关的注释。服务器

/**
 * TcpAsyncServer.java
 */

import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.net.*;
import java.util.Iterator;

public class TcpAsyncServer {

    /*监听端口*/
    int port = 6000;
    /*缓冲区大小*/
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    /*其它相关定义*/
    Selector selector;
    ServerSocketChannel channel;
    ServerSocket socket;

    /*启动*/
    public void Start() throws Exception {
        /*初始化一个Selector*/
        selector = Selector.open();
        /*打开通道*/
        channel = ServerSocketChannel.open();
        /*非阻塞模式*/
        channel.configureBlocking(false);
        /*本机IP*/
        //InetAddress ip = InetAddress.getByName("127.0.0.1");
        InetAddress ip = InetAddress.getLocalHost();
        System.out.println(ip.toString());
        /*绑定IP和端口*/
        InetSocketAddress address = new InetSocketAddress(ip,port);
        socket = channel.socket();
        socket.bind(address);
        /*启动监听*/
        System.out.println("TCP服务器开始监听...");
        Listen();
    }

    /*中止*/
    public void Stop() throws Exception {
        channel.close();
        selector.close();
    }

    /*监听*/
    public void Listen() throws Exception {
        /*注册接收事件*/
        channel.register(selector,SelectionKey.OP_ACCEPT);
        /*无限循环*/
        while (true) {
            selector.select();
            /*轮询事件*/
            Iterator iter = selector.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key =  (SelectionKey)iter.next();
                iter.remove();
                /*事件分类处理*/
                if (key.isAcceptable()) {
                    ServerSocketChannel ssc = (ServerSocketChannel)key.channel();
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    sc.register(selector, SelectionKey.OP_READ);
                    System.out.println("新终端已链接:"+ sc.getRemoteAddress());
                }
                else if (key.isReadable()) {
                    SocketChannel sc = (SocketChannel)key.channel();
                    int recvCount = sc.read(buffer);
                    if (recvCount > 0) {
                        byte[] arr = buffer.array();
                        System.out.println(sc.getRemoteAddress() + "发来数据: "+ new String(arr));
                        buffer.flip();
                    }
                    else {
                        sc.close();
                    }
                    buffer.clear();
                }

                else {

                }


            }

        }

    }

}
/**
 * server.java
 */

public class server {

    public static void main(String[] args) throws Exception {

        TcpAsyncServer tcpServer = new TcpAsyncServer();
        tcpServer.Start();

    }
}

 

效果演示:多线程

1. 利用TCP工具发送数据异步

3. 接收数据socket

相关文章
相关标签/搜索