是否可以通过 websocket 调用 http API?

Is it possible to call http API by websocket?

我被要求使用 websocket 和 php Ratchet 在工作时进行 api 调用。由于我对 websocket 完全不熟悉,所以我搜索并观看了 youtube 视频来解决这个问题,但是我搜索得越多,我就越觉得不可能用 websocket 调用 api。

我是不是遗漏了什么或者真的不可能通过 websocket 调用 api? 如果可能的话,你能给我一个例子吗

我知道我可能听起来很尴尬,因为我对 websockets 没有深入的了解,英语甚至不是我的母语,但我真的很绝望请帮助我

REST API 从根本上不同于 WebSocket API。

休息 API

通过 HTTP(S) 进行调用。您可以使用 AJAX(参见此处:https://en.wikipedia.org/wiki/Ajax_(programming)) to access HTTP endpoints directly from the browser. In JavaScript you would use the Fetch-API (see here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)拨打电话。根据定义,每个调用都是无状态的。 Cookie 和特殊 headers 必须随每个创建上下文的请求一起发送(例如,已登录的用户)。

示例(客户端):

fetch('http://example.com/my-rest-api/endpoint1')
  .then(response => response.json())
  .then(data => console.log(data));

示例(服务器):

app.get('/my-rest-api/endpoint1', handlerFunc);

WebSocketAPI

必须在客户端和服务器之间建立状态连接。客户端和服务器可以通过连接交换消息。不像 REST-API 消息可以双向发送。 WebSocket API 的 high-level 实现是 Socket.io。 API 可以通过定义带有有效负载的消息类型来设计。 我也不建议将 PHP 用于 WS-API(即使有像 Ratchet 这样的解决方案)。使用为 event-based 这样的用例(例如 nodeJS)开发的 language/runtime。

示例(客户端):

const socket = SocketClass('example.com/my-websocket-api');

// variant 1 with callbacks
const response = socket.sendMessage('endpoint1', myData);

// variant 2 with message listener
socket.on('endpoint1Response', handlerFunc);
socket.sendMessage('endpoint1', myData);

示例(服务器):

const serverSocket = SocketClass('/my-websocket-api');
serverSocket.on('connection', function (socket) {

    // variant 1 with callbacks
    socket.on('endpoint1', (data, callback) => {
        callback(null, responseData);
    });

    // variant 2 with message listener
    socket.on('endpoint1', (data, cb) => {
        socket.emit('endpoint1Answer', responseData);
    });
});