之前一直采用.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. 接收数据
时间: 2024-10-25 13:16:42