老师,求助

来源:4-7 测试web端携手移动端与后端netty聊天通信

慕尼黑0536602

2020-12-15

老师,我检查了ws的端口号与我服务器的一致,但是不知道为啥浏览器老是报这个错误:

index.html:20 WebSocket connection to 'ws://192.168.1.1:8088/ws' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED

这是我本地的ip:
图片描述

这是我的前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>请输入消息</div>
    <input type="text" id="contentMsg">
    <input type="button" value="点我发送" onclick="CHAT.chat()">

    <div>收到消息</div>
    <div id="receiveMsg" style="background-color: aqua;"></div>
    <script type="application/javascript">
    window.CHAT={
        socket : null,
        init :function(){
            if(window.WebSocket){
                CHAT.socket = new WebSocket("ws://192.168.1.1:8088/ws");
                CHAT.socket.onopen = function(){
                    console.log("连接成功..");

                },
                CHAT.socket.onerror = function(){
                    console.log("连接错误");

                },
                CHAT.socket.onclose = function(){
                    console.log("连接关闭");

                },
                CHAT.socket.onmessage = function(e){
                    console.log("接收到内容: " + e.data);
                    //获取要打印内容位置的id
                    var receiveMsg = document.getElementById("receiveMsg");
                    var html = receiveMsg.innerHTML;
                    receiveMsg.innerHTML = html +"<br/>"+e.data;


                }


            }
            else{
                alert("浏览器不支持websocket");
            }

        },
        chat : function(){
            var msg = document.getElementById("contentMsg");
            //发送
            CHAT.socket.send(msg.value);

        }
    };
    CHAT.init();

    </script>
    
</body>
</html>

主服务器的代码:

package imooc.netty.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class WSServer {

	public static void main(String[] args) throws Exception {
		//1.主线程
		EventLoopGroup mainGroup = new NioEventLoopGroup();
		//2.从线程
		EventLoopGroup subGroup = new NioEventLoopGroup();
		
		try {
		//定义一个启动类
		ServerBootstrap serverBootstrap = new ServerBootstrap();
		serverBootstrap.group(mainGroup, subGroup)
		               .channel(NioServerSocketChannel.class)
		               .childHandler(new WSServerInitializer());
		
		//为启动类绑定端口号
		ChannelFuture future = serverBootstrap.bind(8088).sync();
		
		//设置一个关闭的channel:
		future.channel().closeFuture().sync();
		}finally {
			mainGroup.shutdownGracefully();
			subGroup.shutdownGracefully();
		}
		

	}

}

自定义的initializer:

package imooc.netty.websocket;

import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WSServerInitializer extends ChannelInitializer<SocketChannel> {

	@Override
	protected void initChannel(SocketChannel channel) throws Exception {
		// 利用channel调出pipeline
		ChannelPipeline pipeline = channel.pipeline();
		
		//利用pipeline添加各个子类handler:
		pipeline.addLast(new HttpServerCodec());
		pipeline.addLast(new ChunkedWriteHandler());
		pipeline.addLast(new HttpObjectAggregator(1024*64));
		
		//====================websocket========的配置
		pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
		
		//自定义handler
		pipeline.addLast(new WSSCustomHandler());
		
	}

}

自定义的handler:

package imooc.netty.websocket;

import java.time.LocalDateTime;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;

public class WSSCustomHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
public static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
	 //把客户端的消息拿出来
		String content = msg.text();
		System.out.println("接收到的消息为 : "+ content);
		
		//我们把服务器获取到的数据,刷到客户端
		clients.writeAndFlush(new TextWebSocketFrame("[服务器]在:"+ LocalDateTime.now()
		+" 获取到消息:" +content));
		
	}

	@Override
	public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
		clients.add(ctx.channel());
	}

	@Override
	public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
		// 当触发handlerRemoved,ChannelGroup会自动移除对应客户端的channel
//		clients.remove(ctx.channel());
		System.out.println("客户端断开,channle对应的长id为:" 
							+ ctx.channel().id().asLongText());
		System.out.println("客户端断开,channle对应的短id为:" 
							+ ctx.channel().id().asShortText());
	}


}

我对照您的代码查了好几次,都找不到问题。。麻烦您帮我看下,谢谢您!

写回答

1回答

风间影月

2020-12-15

不能用浏览器测试。手机端的也在手机上测试呢

0
1
慕尼黑0536602
嗨老师,昨晚整太晚,估计操作不当,今天早上起来,手机端跟网页端都重新试了。全work了! 谢谢老师!
2020-12-15
共1条回复

Netty+Spring Boot仿微信-全栈开发高性能后台及客户端

SpringBoot/Netty+MUI全栈开发 同时搞定后台+ Android&iOS

1498 学习 · 684 问题

查看课程