一个最简单基于spring的websocket服务端+客户端实现案例

1、服务端

代码分为两部分:

一个是服务器终端类:用java注解来监听连接@ServerEndpoint、连接成功@OnOpen、连接失败@OnClose、收到消息等状态@OnMessage

import org.springframework.stereotype.Component;

import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;

@Component
@ServerEndpoint("/websocket/fqa")
public class QwenWebSocket {

    @OnOpen
    public void onOpen(Session session){
        System.out.println("WebSocket opened: " + session.getId());
    }

    @OnMessage
    public void onMessage(String message, Session session){
        System.out.println("Message received: " + message);
        try{
            session.getBasicRemote().sendText("Echo: " + message);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(Session session){
        System.out.println("WebSocket closed: " + session.getId());
    }

    @OnError
    public void onError(Throwable t){
        t.printStackTrace();
    }
}

一个是websocket的配置类,用于把spring中的ServerEndpointExporter对象注入进来

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WebSocketConfig {
    /**
     * 这个bean的注册,用于扫描带有@ServerEndpoint的注解成为websocket,如果你使用外置的tomcat就不需要该配置文件
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

2、客户端

普通的java工程即可,不需要是spring。

import javax.websocket.*;
import java.net.URI;


@ClientEndpoint
public class MyWebSocketClient {

    @OnOpen
    public void onOpen(Session session){
        System.out.println("Connected to server");
    }

    @OnMessage
    public void onMessage(String message){
        System.out.println("Received message: " + message);
    }

    @OnClose
    public void onClose(CloseReason reason){
        System.out.println("Closing: " + reason.getReasonPhrase());
    }

    public static void main(String[] args) {
        try{
            WebSocketContainer container = ContainerProvider.getWebSocketContainer();
            URI uri = URI.create("ws://localhost:8080/websocket/fqa");
            Session session = container.connectToServer(MyWebSocketClient.class, uri);
            session.getBasicRemote().sendText("I'm client!");
            Thread.sleep(10000);
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}

3、效果

客户端显示:

Connected to server
Received message: Echo: I'm client!

服务端显示:

WebSocket opened: 4
Message received: I'm client!
WebSocket closed: 4

以下是一个使用 Netty 实现 WebSocket 服务端客户端的示例代码: 服务端代码: ```java public class WebSocketServer { public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap() .group(group) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpServerCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketServerProtocolHandler("/chat")); pipeline.addLast(new TextWebSocketFrameHandler()); } }); ChannelFuture future = bootstrap.bind(8080).sync(); future.channel().closeFuture().sync(); } finally { group.shutdownGracefully(); } } private static class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> { private final List<Channel> channels = new ArrayList<>(); @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { String text = msg.text(); System.out.println("Received message: " + text); for (Channel channel : channels) { channel.writeAndFlush(new TextWebSocketFrame("Server: " + text)); } } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { channels.add(ctx.channel()); } @Override public void handlerRemoved(ChannelHandlerContext ctx) throws Exception { channels.remove(ctx.channel()); } } } ``` 客户端代码: ```java public class WebSocketClient { public static void main(String[] args) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker( new URI("ws://localhost:8080/chat"), WebSocketVersion.V13, null, false, new DefaultHttpHeaders())); Bootstrap bootstrap = new Bootstrap() .group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); pipeline.addLast(new HttpClientCodec()); pipeline.addLast(new HttpObjectAggregator(65536)); pipeline.addLast(new WebSocketClientProtocolHandler(handler.handshaker())); pipeline.addLast(handler); } }); Channel channel = bootstrap.connect("localhost", 8080).sync().channel(); handler.handshakeFuture().sync(); BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); while (true) { String line = reader.readLine(); if (line == null) { break; } channel.writeAndFlush(new TextWebSocketFrame(line)); } } finally { group.shutdownGracefully(); } } private static class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> { private final WebSocketClientHandshaker handshaker; private ChannelPromise handshakeFuture; public WebSocketClientHandler(WebSocketClientHandshaker handshaker) { this.handshaker = handshaker; } public ChannelFuture handshakeFuture() { return handshakeFuture; } @Override public void handlerAdded(ChannelHandlerContext ctx) throws Exception { handshakeFuture = ctx.newPromise(); } @Override public void channelActive(ChannelHandlerContext ctx) throws Exception { handshaker.handshake(ctx.channel()); } @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception { System.out.println("WebSocket Client disconnected!"); } @Override protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception { if (!handshaker.isHandshakeComplete()) { handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg); System.out.println("WebSocket Client connected!"); handshakeFuture.setSuccess(); return; } if (msg instanceof FullHttpResponse) { FullHttpResponse response = (FullHttpResponse) msg; throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() + ", content=" + response.content().toString(CharsetUtil.UTF_8) + ')'); } TextWebSocketFrame frame = (TextWebSocketFrame) msg; System.out.println("Received message: " + frame.text()); } } } ``` 这个示例代码启动了一个 WebSocket 服务器,监听本地的 8080 端口。当有新的 WebSocket 连接建立时,服务器会将连接加入到一个列表中,当有消息发送到服务器时,服务器会将消息转发给所有连接。同时,客户端与服务器建立连接,发送消息并接收服务器返回的消息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值