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
原创粉丝点击