簡體   English   中英

有沒有辦法在 java 應用程序中創建 websocket 客戶端以與 node.js ZBF56D7Z8B1852CDB29673 服務器通信?

[英]Is there a way to create a websocket client inside a java app to communicate with a node.js websocket server?

Currently, I'm working on a java spring app that runs on a tomcat server and I want to create a WebSocket client there to communicate with a node.js websocket server that running locally. 我找不到客戶的任何實現。 客戶端必須在視圖內(.jsp 文件)還是在 controller 中? websocket 客戶端必須在 web 應用程序中。

下面是 node.js 服務器的實現:

const WebSocket = require('ws');
const express = require('express')
const app = express()
const server = require('http').createServer(app);

const wss = new WebSocket.Server({ server:server });

wss.on('connection', function connection(ws) {
    console.log('A new client Connected!');

    ws.binaryType = 'arraybuffer';
    ws.on('message', function incoming(message) {
    
        const array = new Int16Array(message);
        
        //console.log(array);
        console.log(new Date().toLocaleString().replace(',',' ')+" " + ' Data received');
        ws.send('The server received the message!'); 
    });
});
server.listen(3000, () => console.log(`Lisening on port :3000`))

如果你使用js,你應該使用WebSocket js obj來實現它。 網上還有更多樣片。 我猜你想在 java 中構建一個 websocket 客戶端。 所以你可以參考這個來構建客戶端。 下面是簡單的演示。

maven 依賴

        <dependency>
            <groupId>org.java-websocket</groupId>
            <artifactId>Java-WebSocket</artifactId>
            <version>1.5.1</version>
        </dependency>

websocket客戶端

public class MyWebSocketClient extends WebSocketClient {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyWebSocketClient.class);

    public MyWebSocketClient(URI serverUri) {
        super(serverUri);
    }

    @Override
    public void onOpen(ServerHandshake arg0) {
        // TODO Auto-generated method stub
        LOGGER.info("------ MyWebSocket onOpen ------");
    }

    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        // TODO Auto-generated method stub
        LOGGER.info("------ MyWebSocket onClose ------{}",arg1);
    }

    @Override
    public void onError(Exception arg0) {
        // TODO Auto-generated method stub
        LOGGER.info("------ MyWebSocket onError ------{}",arg0);
    }

    @Override
    public void onMessage(String arg0) {
        // TODO Auto-generated method stub
        LOGGER.info("-------- receive data from websocket server: " + arg0 + "--------");
    }
}

定義要使用的 bean


@SpringBootApplication
public class WebSocketApplication {
    public static void main(String[] args){
        SpringApplication.run(WebSocketApplication.class, args);
    }

        @Bean
    public WebSocketClient webSocketClient() {
        try {
            MyWebSocketClient webSocketClient = new MyWebSocketClient(new URI("ws://127.0.0.1:3000/connection"));
            webSocketClient.connect();
            return webSocketClient;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return null;
    }
   
}


在 restController 中調用

@RestController
public class WebSocketController {

    @Autowired
    private WebSocketClient webSocketClient;

    @RequestMapping("subscribe")
    public String subscribe() {
        webSocketClient.send("hello sever,i want subscribe data A");
        return "send ok";
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM