您的位置:首页 > 其它

Netty学习-02-SocketChannel

2018-04-10 11:12 302 查看
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();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Netty