gpt4 book ai didi

How to connect with socketio build in laravel >laravel-echo-server, from nodejs(如何从NodeJS连接到laravel>laravel-echo-server中的Socketio Build)

转载 作者:bug小助手 更新时间:2023-10-25 16:59:04 32 4
gpt4 key购买 nike



First Approch: Using laravel Echo from node side

第一种方法:从节点侧使用Laravel Echo


I'm trying to connect socketio server using laravel-Echo package from nodejs
as follwing:

我正在尝试使用NodeJS的laravel-Echo包连接Socketio服务器,如下所示:


const express = require("express");
const path = require("path");
const app = express();
const ioClient = require("socket.io-client");
// const socketio = require("socket.io");
const Echo = require("laravel-echo");

this.echo = new Echo({
broadcaster: 'socket.io',
host: 'localhost' + ':' + 6001,
client: ioClient,
logToConsole: true,
transports: ['websocket', 'polling', 'flashsocket'],
});
console.log(echo);

this.echo.channel('close-flare').listen('.CloseFlareEvent', data => {
console.log(data);
});

app.use(express.static(path.join(__dirname, "..", "public")));
module.exports = app;


when I console.log(this.echo) object inside node console returned as follows:

当I console.log(this.ho)对象在节点控制台内返回时,返回如下:


Echo {
options: {
broadcaster: 'socket.io',
host: 'localhost:6001',
client: <ref *1> [Function: lookup] {
managers: [Object],
io: [Circular *1],
protocol: [Getter],
connect: [Circular *1],
Manager: [Getter]
},
logToConsole: true,
transports: [ 'websocket', 'polling', 'flashsocket' ]
},
connector: SocketIoConnector {
_defaultOptions: {
auth: [Object],
authEndpoint: '/broadcasting/auth',
broadcaster: 'socket.io',
csrfToken: null,
host: 'localhost:6001',
key: null,
namespace: 'App.Events',
client: [Function],
logToConsole: true,
transports: [Array],
path: '/socket.io',
hostname: 'undefined',
secure: false,
port: '80'
},
options: {
auth: [Object],
authEndpoint: '/broadcasting/auth',
broadcaster: 'socket.io',
csrfToken: null,
host: 'localhost:6001',
key: null,
namespace: 'App.Events',
client: [Function],
logToConsole: true,
transports: [Array],
path: '/socket.io',
hostname: 'undefined',
secure: false,
port: '80'
},
socket: Socket {
receiveBuffer: [],
sendBuffer: [],
ids: 0,
acks: {},
flags: {},
io: [Manager],
nsp: '//localhost:6001',
connected: false,
disconnected: true,
auth: [Object],
subs: [Array],
_callbacks: [Object]
},
channels: {}
}
}

but the problem that when I send an event from laravel it doesn't come in the node server. However, I do get the event message if I call it from the browser-side as follows:

但问题是,当我从laravel发送事件时,它不会出现在节点服务器中。但是,如果我按如下方式从浏览器端调用它,我确实会收到事件消息:


this code works well on the browser-side:

这段代码在浏览器端运行良好:


const Echo = require("laravel-echo");
window.Echo = new Echo({
broadcaster: "socket.io",
host: window.location.hostname + ":" + 6001,
logToConsole: true,
transports: ["websocket", "polling", "flashsocket"],
});
console.log(window.Echo);
window.Echo.channel("close-flare").listen(
".CloseFlareEvent",
(data) => {
console.log(data);
}
);


php >laravel establishing code:

Php>laavel建立代码:


this code establishes the channel and the event inside larvel

这段代码建立了Larvel内部的通道和事件


<?php

namespace App\Events;

use Illuminate\Broadcasting\Channel;
use Illuminate\Broadcasting\InteractsWithSockets;
use Illuminate\Broadcasting\PresenceChannel;
use Illuminate\Broadcasting\PrivateChannel;
use Illuminate\Contracts\Broadcasting\ShouldBroadcast;
use Illuminate\Contracts\Broadcasting\ShouldBroadcastNow;
use Illuminate\Foundation\Events\Dispatchable;
use Illuminate\Queue\SerializesModels;

class CloseFlareByTrader implements ShouldBroadcastNow
{
use InteractsWithSockets, SerializesModels;

/**
* Create a new event instance.
*
* @return void
*/

public $flare_id;

public function __construct($flare_id)
{
$this->flare_id = $flare_id;
}

/**
* Get the channels the event should broadcast on.
*
* @return \Illuminate\Broadcasting\Channel|array
*/

public function broadcastOn()
{
return new Channel('close-flare');
}

/**
* The event's broadcast name.
*
* @return string
*/
public function broadcastAs()
{
return 'CloseFlareEvent';
}

/**
* The event's broadcast name.
*
* @return string
*/
public function broadcastWith()
{
return ['flare_id' => $this->flare_id];
}
}


Second Approch: Trying to use WebSocket instead of laravel Echo inside node

第二种方法:尝试在节点内部使用WebSocket而不是laravel Echo


If I tried to connect the socket using WebSocket as follow:

如果我尝试使用WebSocket连接套接字,如下所示:


const WebSocket = require("ws");
var ws = new WebSocket("http://localhost:6001/socket.io?transport=websocket");


I get the following error on the node side:

我在节点端得到以下错误:


events.js:292
throw er; // Unhandled 'error' event
^

Error: socket hang up
at connResetException (internal/errors.js:607:14)
at Socket.socketOnEnd (_http_client.js:493:23)
at Socket.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21)
Emitted 'error' event on WebSocket instance at:
at ClientRequest.<anonymous> (C:\Users\Ahmad\Desktop\New folder\node_modules\ws\lib\websocket.js:579:15)
at ClientRequest.emit (events.js:315:20)
at Socket.socketOnEnd (_http_client.js:493:9)
at Socket.emit (events.js:327:22)
at endReadableNT (internal/streams/readable.js:1327:12)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
code: 'ECONNRESET'
}

And in the laravel-echo-server I get:

在LALAVEL-ECHO-SERVER中,我得到:


events.js:292
throw er; // Unhandled 'error' event
^

Error: read ECONNRESET
at TCP.onStreamRead (internal/stream_base_commons.js:209:20)
Emitted 'error' event on Socket instance at:
at emitErrorNT (internal/streams/destroy.js:106:8)
at emitErrorCloseNT (internal/streams/destroy.js:74:3)
at processTicksAndRejections (internal/process/task_queues.js:80:21) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}


更多回答
优秀答案推荐

I had a similar problem with react-native. I wanted to connect to a laravel-echo server. larave-echo-server was working fine and was sending signals on the client side of larave but could not get signals in react native.

This is my react-native with larave-echo and socket.io-client setup

我也遇到过类似的Reaction-Native问题。我想连接到一台LALAVEL-ECHO服务器。LARLAVE-ECHO-SERVER工作正常,并在LARLAVE的客户端发送信号,但在REACTION本机中无法获得信号。这是我使用larave-echo和Socket.IO-CLIENT设置的原生反应


useEffect(() => {
const echo = new Echo({
broadcaster: 'socket.io',
host: `wss://${host}:6001`,
client: io,
});

const channel = echo.channel('trading-signal');
channel.listen('TradingSignalEvent', e => {
console.log('Received trading signal:', e.trading_signal);
if (e.trading_signal) {
setTradingSignal(e.trading_signal)
}
});
echo.connector.socket.on('connect', () => {
console.log('Successfully connected.');
});

echo.connector.socket.on('connect_error', (error) => {
console.error('Error Message:', error.message);
});
// Cleanup function
return () => {
console.log('stopListening')
channel.stopListening('TradingSignalEvent');
echo.disconnect();
};
}, []);

Import at the top:

在顶部导入:


import Echo from 'laravel-echo';
import io from 'socket.io-client';

My problem was that I used different socket.io package versions on react-native side from backend. When I downgraded on react-native to:

我的问题是,我在Reaction本机端和后端使用了不同的Socket.IO包版本。当我将Reaction-Native降级为:


"socket.io": "^2.5.0",
"socket.io-client": "^2.5.0"

it started working.

它开始起作用了。


Also you should check if you have correctly configured larave-echo-server.json file. For https(wss) you need to declare ssl certificate path.

此外,您还应该检查是否正确配置了larave-ho-server.json文件。对于HTTPS(Wss),您需要声明SSL证书路径。


{
"authHost": "http://localhost",
"authEndpoint": "/broadcasting/auth",
"clients": [],
"database": "redis",
"databaseConfig": {
"redis": {},
"sqlite": {
"databasePath": "/database/laravel-echo-server.sqlite"
}
},
"devMode": false,
"host": null,
"port": "6001",
"protocol": "https",
"socketio": {},
"secureOptions": 67108864,
"sslCertPath": "/etc/letsencrypt/live/domain.com/fullchain.pem",
"sslKeyPath": "/etc/letsencrypt/live/domain.com/privkey.pem",
"sslCertChainPath": "",
"sslPassphrase": "",
"subscribers": {
"http": true,
"redis": true
},
"apiOriginAllow": {
"allowCors": false,
"allowOrigin": "",
"allowMethods": "",
"allowHeaders": ""
}
}

更多回答

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