java NIO Socket通信

直接上代码
Server 端代码

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class NIOServer {
    private Selector selector;
    public void  initServer(int port) throws IOException{
        ServerSocketChannel channel = ServerSocketChannel.open();
        channel.configureBlocking(false);
        channel.socket().bind(new InetSocketAddress(port));
        this.selector = Selector.open();
        //注册到selector等待连接
        channel.register(selector, SelectionKey.OP_ACCEPT);
    }
    public void listen() throws IOException{
        System.out.println("服务端启动成功");
        while(true)
        {
            selector.select();
            Iterator it = this.selector.selectedKeys().iterator();
            while(it.hasNext())
            {
                SelectionKey key = (SelectionKey) it.next();
                it.remove();
                if(key.isAcceptable())
                {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel channel = server.accept();
                    channel.configureBlocking(false);
                    //给客户端发送消息
                    channel.write(ByteBuffer.wrap(new String("向客户端发送了一条消息").getBytes()));
                    channel.register(selector, SelectionKey.OP_READ);
                }
                else if(key.isReadable())
                {
                    read(key);
                }
            }
        }
    }
    public void read(SelectionKey key) throws IOException{
        SocketChannel channel = (SocketChannel) key.channel();  
        // 创建读取的缓冲区  
        ByteBuffer buffer = ByteBuffer.allocate(1024);  
        channel.read(buffer);
        byte[] data = buffer.array();  
        String msg = new String(data).trim();  
        System.out.println("服务端收到信息:"+msg);
        channel.register(selector, SelectionKey.OP_READ);
    }

    public static void main(String[] args) throws IOException {
        NIOServer server = new NIOServer();
        server.initServer(9000);
        server.listen();
    }

}

Client端代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
public class NIOClient {
    /*
     * 客户端
     */
    private Selector selector;

    public void initClinet(String ip, int port) throws IOException
    {
        //获得一个Socket通道
        SocketChannel channel = SocketChannel.open();
        //设置通道为非阻塞
        channel.configureBlocking(false);
        this.selector = Selector.open();
        channel.connect(new InetSocketAddress(ip,port));
        channel.register(selector, SelectionKey.OP_CONNECT);
    }
    public void listen() throws IOException{
        System.out.println("客户端启动");
        while(true)
        {
            selector.select();
            Iterator it = this.selector.selectedKeys().iterator();
            while(it.hasNext())
            {
                SelectionKey key = (SelectionKey) it.next();
                it.remove();
                if(key.isConnectable())
                {
                    SocketChannel channel = (SocketChannel) key.channel();
                    //如果正在连接 完成连接
                    if(channel.isConnectionPending())
                    {
                        channel.finishConnect();
                    }
                    channel.configureBlocking(false);
                    //给服务端发送消息
                    channel.write(ByteBuffer.wrap(new String("向服务端发送一条消息").getBytes()));
                    //为了可以接受服务端的消息 需要给通道设置读的权限
                    channel.register(this.selector, SelectionKey.OP_READ);
                }
                else if(key.isReadable())
                {
                    read(key);
                }
                else if(key.isWritable()) 
                {
                    write(key);
                }
            }
        }
    }

    public void write(SelectionKey key){
        SocketChannel channel = (SocketChannel) key.channel(); 
        InputStreamReader fis = new InputStreamReader(System.in);
        BufferedReader bf = new BufferedReader(fis);
        try {
            ByteBuffer outBuffer = ByteBuffer.wrap(bf.readLine().getBytes());  
            channel.write(outBuffer);// 将消息回送给客户端  
        } catch (Exception e) {
        }
    }

    public void read(SelectionKey key) throws IOException{
        SocketChannel channel = (SocketChannel) key.channel();  
        // 创建读取的缓冲区  
        ByteBuffer buffer = ByteBuffer.allocate(1024);  
        channel.read(buffer);  
        byte[] data = buffer.array();  
        String msg = new String(data).trim();  
        System.out.println("客户端收到信息:"+msg);
        channel.register(selector,SelectionKey.OP_WRITE);
        //ByteBuffer outBuffer = ByteBuffer.wrap(msg.getBytes());  
        //channel.write(outBuffer);// 将消息回送给客户端  

    }
    public static void main(String[] args) throws IOException {
        NIOClient client = new NIOClient();
        client.initClinet("127.0.0.1", 9000);
        client.listen();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
毕业设计,基于SpringBoot+Vue+MySQL开发的精简博客系统,源码+数据库+毕业论文+视频演示 当下,正处于信息化的时代,许多行业顺应时代的变化,结合使用计算机技术向数字化、信息化建设迈进。以前企业对于博客信息的管理和控制,采用人工登记的方式保存相关数据,这种以人力为主的管理模式已然落后。本人结合使用主流的程序开发技术,设计了一款基于Springboot开发的精简博客系统,可以较大地减少人力、财力的损耗,方便相关人员及时更新和保存信息。本系统主要使用B/S开发模式,在idea开发平台上,运用Java语言设计相关的系统功能模块,MySQL数据库管理相关的系统数据信息,SpringBoot框架设计和开发系统功能架构,最后通过使用Tomcat服务器,在浏览器中发布设计的系统,并且完成系统与数据库的交互工作。本文对系统的需求分析、可行性分析、技术支持、功能设计、数据库设计、功能测试等内容做了较为详细的介绍,并且在本文中也展示了系统主要的功能模块设计界面和操作界面,并对其做出了必要的解释说明,方便用户对系统进行操作和使用,以及后期的相关人员对系统进行更新和维护。本系统的实现可以极大地提高企业的工作效率,提升用户的使用体验,因此在现实生活中运用本系统具有很大的使用价值。 关键词:博客管理;Java语言;B/S结构;MySQL数据库
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值