gpt4 book ai didi

Redux Saga socket.io

转载 作者:行者123 更新时间:2023-12-05 05:11:35 24 4
gpt4 key购买 nike

我目前正在开发一个聊天客户端,它必须能够接收消息和发送消息。我面临的唯一问题是我真的不知道如何在 Saga 示例的给定组件内发送消息。

我在他们的 API 文档中找到了这个例子 https://redux-saga.js.org/docs/advanced/Channels.html .

我能否重用我在 watchSocketChannel 函数中创建的套接字常量?还是我只需要创建连接两次?你会建议做什么?

import {all, apply, call, fork, put, take} from 'redux-saga/effects'
import {eventChannel} from 'redux-saga';
import * as actions from "../actions";
import io from 'socket.io-client';

function createSocketConnection(url, namespace) {
return io(url + '/' + namespace);
}

function createSocketChannel(socket) {
return eventChannel(emit => {
const eventHandler = (event) => {
emit(event.payload);
};

const errorHandler = (errorEvent) => {
emit(new Error(errorEvent.reason));
};

socket.on('message', eventHandler);
socket.on('error', errorHandler);

const unsubscribe = () => {
socket.off('message', eventHandler);
};

return unsubscribe;
});
}

function* emitResponse(socket) {
yield apply(socket, socket.emit, ['message received']);
}

function* writeSocket(socket) {
while (true) {
const { eventName, payload } = yield take(actions.WEBSOCKET_SEND);
socket.emit(eventName, payload);
}
}

function* watchSocketChannel() {
const socket = yield call(createSocketConnection, 'http://localhost:3000', 'terminal');
const socketChannel = yield call(createSocketChannel, socket);

console.log(socket);

while (true) {
try {
const payload = yield take(socketChannel);
yield put({type: actions.WEBSOCKET_MESSAGE, payload});
yield fork(emitResponse, socket);
} catch (err) {
console.log('socket error: ', err);
}
}
}

export default function* root() {
yield all([
fork(watchSocketChannel),
])

我知道fork函数是把watchSocketChannel函数附加到saga上,不断监听。

最佳答案

我不确定我是否正确理解了你的问题......如果你问如何/在哪里 fork writeSocket saga 以允许你发送 actions.WEBSOCKET_SEND) 操作并将您的消息发送到套接字:

在创建套接字 channel 的过程中添加一个分支还不够吗?

const socket = yield call(createSocketConnection, 'http://localhost:3000', 'terminal');
fork(writeSocket, socket); // I've added this line
const socketChannel = yield call(createSocketChannel, socket);

关于Redux Saga socket.io,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55303250/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com