import { OnModuleInit } from "@nestjs/common";
import { WebSocketGateway, SubscribeMessage, MessageBody, WebSocketServer } from "@nestjs/websockets";
import { Server } from 'socket.io';
@WebSocketGateway({
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
allowedHeaders: ["Content-Type"],
credentials: true
},
namespace: '/'
})
export class MyGateway implements OnModuleInit {
@WebSocketServer()
server: Server;
onModuleInit() {
this.server.on('connection', socket => {
console.log('Connected ', socket.id);
});
}
@SubscribeMessage('newMessage')
onNewMessage(@MessageBody() body: any) {
console.log(body);
this.server.emit('onMessage', {
msg: 'New Message',
content: body,
});
}
}
'use client';
import React, { useEffect } from 'react';
import { io } from 'socket.io-client';
const WebSocketComponent = () => {
useEffect(() => {
const socket = io('http://localhost:3001');
socket.on('connect', () => {
console.log('Connected to WebSocket server');
});
const sendMessage = () => {
socket.emit('newMessage', { text: 'Hello, World!' });
};
sendMessage();
socket.on('onMessage', data => {
console.log('Received:', data);
});
return () => {
socket.disconnect();
};
}, []);
return <div>WebSocket Component</div>;
};
export default WebSocketComponent;
page.tsx:7
GET http://localhost:3001/socket.io/?EIO=4&transport=polling&t=6dbxeyn2 net::ERR_CONNECTION_REFUSED