NIO实现socket实例

转载:https://www.cnblogs.com/guazi/p/6605221.html,
https://www.cnblogs.com/xrq730/p/5186065.html
14年的一篇:https://www.cnblogs.com/davidwang456/p/3831560.html:
///client端和main()方法:
public class SelectorClient
{
private static final String STR = “ROTK NEVER SONG!”;
private static final String REMOTE_IP = “127.0.0.1”;
public void asd()
{
try
{
int port = 1234;
SocketChannel sc = SocketChannel.open();
sc.configureBlocking(false);
sc.connect(new InetSocketAddress(REMOTE_IP, port));
while (!sc.finishConnect())
{
System.out.println(“同” + REMOTE_IP + “的连接正在建立,请稍等!”);
Thread.sleep(10);
}
System.out.println(“连接已建立,待写入内容至指定ip+端口!时间为” + System.currentTimeMillis());
String writeStr = STR;
ByteBuffer bb = ByteBuffer.allocate(writeStr.length());
bb.put(writeStr.getBytes());
bb.flip(); // 写缓冲区的数据之前一定要先反转(flip)
sc.write(bb);
bb.clear();
sc.close();
}
catch (IOException e)
{
e.printStackTrace();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception
{
while(true){
SelectorClient asda = new SelectorClient();
asda.asd();
}
}
}

//客户端:

public class SelectorServer
{
private static int PORT = 1234;
public static void main(String[] args) throws Exception
{
// 先确定端口号
int port = PORT;
if (args != null && args.length > 0)
{
port = Integer.parseInt(args[0]);
}
// 打开一个ServerSocketChannel
ServerSocketChannel ssc = ServerSocketChannel.open();
// 获取ServerSocketChannel绑定的Socket
ServerSocket ss = ssc.socket();
// 设置ServerSocket监听的端口
ss.bind(new InetSocketAddress(port));
// 设置ServerSocketChannel为非阻塞模式
ssc.configureBlocking(false);
// 打开一个选择器
Selector selector = Selector.open();
// 将ServerSocketChannel注册到选择器上去并监听accept事件
ssc.register(selector, SelectionKey.OP_ACCEPT);
while (true)
{
// 这里会发生阻塞,等待就绪的通道
int n = selector.select();
// 没有就绪的通道则什么也不做
if (n == 0)
{
continue;
}
// 获取SelectionKeys上已经就绪的通道的集合
Iterator iterator = selector.selectedKeys().iterator();
// 遍历每一个Key
while (iterator.hasNext())
{
SelectionKey sk = iterator.next();
// 通道上是否有可接受的连接
if (sk.isAcceptable())
{
ServerSocketChannel ssc1 = (ServerSocketChannel)sk.channel();
SocketChannel sc = ssc1.accept();
sc.configureBlocking(false);
sc.register(selector, SelectionKey.OP_READ);
}
// 通道上是否有数据可读
else if (sk.isReadable())
{
readDataFromSocket(sk);
}
iterator.remove();
}
}
}
private static ByteBuffer bb = ByteBuffer.allocate(1024);
// 从通道中读取数据
protected static void readDataFromSocket(SelectionKey sk) throws Exception
{
SocketChannel sc = (SocketChannel)sk.channel();
bb.clear();
while (sc.read(bb) > 0)
{
bb.flip();
while (bb.hasRemaining())
{
System.out.print((char)bb.get());
}
System.out.println();
bb.clear();
}
}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值