4、客户端给服务端发消息,服务端回复

app.js 服务端

/**
 * 服务端
 */

/**
 * 1 将nodejs-websock包引进来
 */
var ws = require('nodejs-websocket');

/**
 * 2 创建一个WebSocket服务,建立TCP连接, 
 * conn就是连进来的连接
 * server 监听2333端口
 */
var server = ws.createServer(function(conn){

    console.log('New connection'); // 表示新的连接进来了
    /**
     * conn绑一个text事件,并接受一个回调
     */
    conn.on('text', function(str){
        console.log(str);
        // 给客户端返回信息
        conn.sendText(str);
    });


}).listen(2333);

index.html 客户端

<!-- 
    客户端
 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <input type="text" id="text">
    <button id="btn" type="button">发送</button>
    <script>
        /**
         * 这里我们创建一个WebSocket,里面填上服务端连接及端口号
         * ws 表示它的协议
         * 
         */
        var ws = new WebSocket('ws://localhost:2333');

        /**
         * 向服务端发送消息
         */
        ws.onopen = function(){
            document.getElementById('btn').onclick = function(){
                ws.send(document.getElementById('text').value);
            }
        }

        /**
         * 接受服务端信息
         */
        ws.onmessage = function(e){
            var p = document.createElement('p');
            p.innerHTML = e.data;
            document.body.appendChild(p);
        } 
    </script>
</body>
</html>

点击【调试】,启动调试,打开页面

当我们关闭网页时会报错

为此我们添加一个error事件

/**
 * 服务端
 */

/**
 * 1 将nodejs-websock包引进来
 */
var ws = require('nodejs-websocket');

/**
 * 2 创建一个WebSocket服务,建立TCP连接, 
 * conn就是连进来的连接
 * server 监听2333端口
 */
var server = ws.createServer(function(conn){

    console.log('New connection'); // 表示新的连接进来了
    /**
     * conn绑一个text事件,并接受一个回调
     */
    conn.on('text', function(str){
        console.log(str);
        // 给客户端返回信息
        conn.sendText(str);
    });

    conn.on("error",function(err){
        console.log(err);
    });
}).listen(2333);



 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,这是一个很好的问题。使用Spring Boot和Netty实现双向通信的过程如下: 1. 首先,在pom.xml中添加以下依赖项: ``` <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.25.Final</version> </dependency> ``` 2. 创建Netty服务器 ``` @Component public class NettyServer { private final EventLoopGroup bossGroup = new NioEventLoopGroup(); private final EventLoopGroup workerGroup = new NioEventLoopGroup(); private Channel channel; @Autowired private NettyServerHandler nettyServerHandler; public void start() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(nettyServerHandler); } }); ChannelFuture f = bootstrap.bind(8888).sync(); if (f.isSuccess()) { System.out.println("Netty server start success"); } channel = f.channel().closeFuture().sync().channel(); } public void stop() throws Exception { channel.close(); bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } ``` 在这个示例中,我们创建了一个名为NettyServer的类。这个类使用了Netty的ServerBootstrap类来创建服务器。在服务器启动时,我们需要指定使用的IO模式和端口号。此外,我们还需要指定NettyServerHandler类,这个类用于处理客户端发来的消息。 3. 创建NettyServerHandler类 ``` @Component @ChannelHandler.Sharable public class NettyServerHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("Server received:" + msg); // 回复客户端 ctx.writeAndFlush("Server received your message: " + msg + "\n"); // 其他业务逻辑 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Server exceptionCaught"); cause.printStackTrace(); ctx.close(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("Server channelActive"); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("Server channelInactive"); super.channelInactive(ctx); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { System.out.println("Server channelReadComplete"); super.channelReadComplete(ctx); } } ``` 在这个示例中,我们创建了一个名为NettyServerHandler的类。这个类用于处理客户端发来的消息。我们需要实现channelRead0方法,这个方法会在客户端发送消息时被调用。在这个方法中,我们可以处理客户端发送的消息,并且回复消息客户端。除此之外,我们还需要实现其他方法,如exceptionCaught、channelActive、channelInactive和channelReadComplete。 4. 创建Netty客户端 ``` @Component public class NettyClient { private Channel channel; private final EventLoopGroup group = new NioEventLoopGroup(); @Autowired private NettyClientHandler nettyClientHandler; public void start() throws Exception { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.TCP_NODELAY, true) .handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new StringDecoder()); pipeline.addLast(new StringEncoder()); pipeline.addLast(nettyClientHandler); } }); ChannelFuture f = bootstrap.connect("localhost", 8888).sync(); if (f.isSuccess()) { System.out.println("Netty client start success"); } channel = f.channel().closeFuture().sync().channel(); } public void stop() throws Exception { channel.close(); group.shutdownGracefully(); } } ``` 在这个示例中,我们创建了一个名为NettyClient的类。这个类使用了Netty的Bootstrap类来创建客户端。在客户端启动时,我们需要指定使用的IO模式和服务器的IP地址和端口号。此外,我们还需要指定NettyClientHandler类,这个类用于处理服务器发来的消息。 5. 创建NettyClientHandler类 ``` @Component @ChannelHandler.Sharable public class NettyClientHandler extends SimpleChannelInboundHandler<String> { @Override protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception { System.out.println("Client received:" + msg); // 其他业务逻辑 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { System.out.println("Client exceptionCaught"); cause.printStackTrace(); ctx.close(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { System.out.println("Client channelActive"); super.channelActive(ctx); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("Client channelInactive"); super.channelInactive(ctx); } @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception { System.out.println("Client channelReadComplete"); super.channelReadComplete(ctx); } } ``` 在这个示例中,我们创建了一个名为NettyClientHandler的类。这个类用于处理服务器发来的消息。我们需要实现channelRead0方法,这个方法会在服务器发送消息时被调用。在这个方法中,我们可以处理服务器发送的消息。除此之外,我们还需要实现其他方法,如exceptionCaught、channelActive、channelInactive和channelReadComplete。 6. 在Spring Boot中启动Netty服务器和客户端 最后,在Spring Boot应用程序的启动类中,我们需要启动Netty服务器和客户端。我们可以使用@PostConstruct注释来启动Netty服务器和客户端。 ``` @SpringBootApplication public class Application { @Autowired private NettyServer nettyServer; @Autowired private NettyClient nettyClient; @PostConstruct public void start() throws Exception { new Thread(() -> { try { nettyServer.start(); } catch (Exception e) { e.printStackTrace(); } }).start(); new Thread(() -> { try { nettyClient.start(); } catch (Exception e) { e.printStackTrace(); } }).start(); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 好了,以上就是使用Spring Boot和Netty实现双向通信的全部过程。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值