Het Shah
Het Shah

Reputation: 21

WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=4&transport=websocket' failed:

This is a simple chat application project with Socket.io, but i am having problem connecting socket.io client which is in React to my server in Node

Connection code for my server is like this

const server = http.createServer(app)
const io = socketio(server, {
  cors: {
    origin: 'http://localhost:3000',
    methods: ['GET', 'POST'],
  }
})

const onSocketConnection = socket => {
    console.log('Socket connected')
    socketConnection(io, socket, db)
  }
  
  io.on("connection", onSocketConnection)

Connection in client side is like this

import io from "socket.io-client"
const socket = io.connect('http://localhost:8000',{  
    cors: {
        origin: "http://localhost:5000",
        credentials: true
    },transports : ['websocket'] 
})

This is the error i am reviving

WebSocket connection to 'ws://localhost:8000/socket.io/?EIO=4&transport=websocket' failed:  

Error snapshot

Upvotes: 1

Views: 8489

Answers (1)

farhad
farhad

Reputation: 226

server side (http://localhost:8000):

import { Server } from 'socket.io';
...
const server = http.createServer(app)
const io = new Server(server, {
  cors: {
    origin: ['http://localhost:3000'],
  }
})

// listening for connections from clients
io.on('connection', (socket) =>{
  // listening to events from client
  socket.on('eventName', (params, callback) => {
     ...
    
    // send data back to client by using ack callback
    callback(data)

    // send data back to client by using emit
    socket.emit('eventName', data)

    // broadcasting data to all other connected clients
    socket.broadcast.emit('eventName', data)
  })  
})

client side (http://localhost:3000):

import { io } from "socket.io-client"
const socket = io('http://localhost:8000',{  
    withCredentials: true
})

// emit:
socket.emit('eventName', params, callback => {
  ...
})


// listen to events from sever:
socket.on('eventName', callback => {
  ...
})

Upvotes: 1

Related Questions