Netty学习-02-SocketChannel
来源:互联网 发布:网络拓扑描述 编辑:程序博客网 时间:2024/05/29 04:35
SocketChannel实现socket编程
(一)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();}}
0 0
- Netty学习-02-SocketChannel
- SocketChannel 学习
- NIO 学习(五) SocketChannel
- Netty学习-02
- SocketChannel
- SocketChannel
- SocketChannel
- Java NIO 学习笔记 - SocketChannel
- Netty学习-05-Netty
- Netty----什么是Netty学习
- netty学习
- Netty学习
- Netty学习
- Netty学习
- Netty学习
- netty 学习
- netty学习
- Netty学习
- 关于远程连接桌面问题
- Linux操作系统基础
- 伪类和伪元素
- 获取MAC地址
- java 使用RabbitMQ示例
- Netty学习-02-SocketChannel
- 欢迎使用CSDN-markdown编辑器
- 线性存储的随机数集合
- Python的设计模式编程入门指南
- Linux下简单进度条实现
- 【Srm590】Fox And City(fox)
- Activity向Service传值1 getdoubleExtra
- C/C++ 书籍目录
- Move Zeroes