首页 > 代码库 > Java--NIO-TCP Socket
Java--NIO-TCP Socket
1、首先我们使用SocketChannel,实现socket客户端
package com.seeyon.nio.socket; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; /** * Created by yangyu on 2017/2/22. */ public class Client { public static void main(String[] args) { try (SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8088))) { socketChannel.configureBlocking(false); ByteBuffer byteBuffer = ByteBuffer.allocate(512); socketChannel.write(ByteBuffer.wrap("this is client send message".getBytes())); while (true) { byteBuffer.clear(); int readBytes = socketChannel.read(byteBuffer); if (readBytes > 0) { byteBuffer.flip(); System.out.println(new String(byteBuffer.array(), 0, readBytes)); socketChannel.close(); break; } } } catch (IOException e) { e.printStackTrace(); } } }
2、使用ServerSocketChannel实现服务端,并且使用Selector
package com.seeyon.nio.socket; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.Iterator; import java.util.Set; /** * Created by yangyu on 2017/2/22. */ public class Server { public static void main(String[] args) throws IOException { ServerSocketChannel serverChannel = ServerSocketChannel.open(); serverChannel.socket().bind(new InetSocketAddress(8088)); serverChannel.configureBlocking(false); Selector selector = Selector.open(); serverChannel.register(selector, SelectionKey.OP_ACCEPT); while (true) { selector.select(); Set<SelectionKey> readyKeys = selector.selectedKeys(); Iterator<SelectionKey> iterator = readyKeys.iterator(); while (iterator.hasNext()) { SelectionKey key = iterator.next(); iterator.remove(); if (key.isAcceptable()) { System.out.println("accept"); ByteBuffer byteBuffer = ByteBuffer.allocate(512); ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); SocketChannel socketChannel = serverSocketChannel.accept(); socketChannel.configureBlocking(false); int readKeys = socketChannel.read(byteBuffer); if (readKeys > 0) { byteBuffer.flip(); System.out.println(new String(byteBuffer.array(), 0, readKeys)); } socketChannel.write(ByteBuffer.wrap("接收到了".getBytes())); } else if (key.isReadable()) { System.out.println("read"); } else if (key.isWritable()) { System.out.println("write"); } } } } }
Java--NIO-TCP Socket
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。