码迷,mamicode.com
首页 > 编程语言 > 详细

Java TCP异步数据接收

时间:2015-11-13 23:39:28      阅读:366      评论:0      收藏:0      [点我收藏+]

标签:

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

综合网上和书本的相关知识,本文给出一个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. 接收数据

技术分享

Java TCP异步数据接收

标签:

原文地址:http://www.cnblogs.com/liuliyang/p/4963381.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!