Netty学习-02-SocketChannel
2018-04-10 11:12
302 查看
SocketChannel实现socket编程
(一)ServerSocketChannel实现服务端
(二)SocketChannel编写客户端
服务端:
客户端
(一)ServerSocketChannel实现服务端
(二)SocketChannel编写客户端
服务端:
import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; public class ServerSocketChannelDemo { public static void startServer() throws Exception{ ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.socket().bind(new InetSocketAddress(8999)); serverSocketChannel.configureBlocking(false);//false为非阻塞 while(true){ SocketChannel socketChannel = serverSocketChannel.accept(); if(socketChannel!=null){ ByteBuffer buf = ByteBuffer.allocate(48); int size =socketChannel.read(buf); while(size>0){ buf.flip();//一定不要少了这句 Charset charset = Charset.forName("UTF-8"); System.out.println(charset.newDecoder().decode(buf));//buf中是二进制流 size =socketChannel.read(buf); } buf.clear(); ByteBuffer response = ByteBuffer.wrap("hello 小美,我已经接受到你的邀请!".getBytes("UTF-8")); socketChannel.write(response); response.clear(); // socketChannel.close(); } } } public static void main(String[] args) throws Exception { startServer(); } }
客户端
import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; public class SocketChannelDemo { public static void startClient() throws Exception { SocketChannel socketChannel = SocketChannel.open(); socketChannel.connect(new InetSocketAddress("localhost", 8999)); String request = "hello 夜行侠老师"; ByteBuffer buf = ByteBuffer.wrap(request.getBytes("UTF-8")); socketChannel.write(buf); ByteBuffer rbuf = ByteBuffer.allocate(48); int size = socketChannel.read(rbuf); while (size > 0) { rbuf.flip(); Charset charset = Charset.forName("UTF-8"); System.out.println(charset.newDecoder().decode(rbuf)); rbuf.clear(); size = socketChannel.read(rbuf); } buf.clear(); rbuf.clear(); socketChannel.close(); Thread.sleep(50000);// 避免Channel马上就关闭 } public static void main(String[] args) throws Exception { startClient(); } }
相关文章推荐
- Netty学习之旅------写事件处理NioSocketChannel、ChannelOutbondBuffer源码分析
- netty学习之ChannelSink(NioClientSocketPipelineSink)
- Netty学习-03-SelectorServerSocketChannel
- Netty学习之NIO---通道Channel(一)
- Netty学习-02(粘包 解包 FrameDecoder)
- netty 学习- channel代码相关注释
- Netty源码学习(五)ChannelInitializer
- Netty学习笔记14 使用Netty-SocketIO 实现简单聊天室程序
- netty学习02-几个核心类以及其介绍
- Java_socket程序学习03-一个客户端对一个服务器-交互(客户端)--02
- Netty学习-02
- Netty学习四:Channel
- netty学习之Channel接口
- 【Netty源码学习】DefaultChannelPipeline(三)
- Java NIO学习8(Selector 补充版ServerSocketChannel)
- netty学习之ServerChannel
- Netty学习笔记之EmbededChannel 单元测试
- 【Netty源码学习】DefaultChannelPipeline(三)
- Java_socket程序学习02-一个客户端对一个服务器-客户端键盘输入
- netty支持的各种socketchannel实现及比较