最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How To Implement React hook Socketio in Next.js - Stack Overflow

programmeradmin0浏览0评论

I have tried to find a way from Google but the results can remain the same

 http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MnHYrvR

i try this wan medium try other ways, the results remain the same

and for the front end I have tried, socket io inside the hook component and outside the scope, the results remain the same

http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MnHYrvR

this is my code from server:

app.prepare().then(() => {
    const server    = express();
    const setServer = require('http').Server(server);
    const io        = require('socket.io')(setServer)

    server.use(bodyParser.json());
    server.use(cookieParser());

    io.on('connection', socket => {
        console.log('socket', socket);

        socket.emit('now', {
            message: 'zeit'
        })
    })


    server.use(routers)

    server.get('*', (req, res) => {
        return handle(req, res);
    });

    server.use( (err, req, res, next) => {
        console.log(err)
        if(err.name === 'Error'){
            res.status(401).send({
                title: 'error',
                detail: 'Unauthorized Access!'
            })
        }
    })

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://heroku:${port}`)
    })
})
.catch(ex => {
    console.error(ex.stack);
    process.exit(1);
});

from front end:

//at the top of function
const io = require('socket.io-client');
const socket = io.connect('http://localhost:8000');
console.log('socket', socket);

//in use effect
useEffect(() =>{
        socket.on('now', message => {
            console.log('message', meesage);
        })
    })

Please help

I have tried to find a way from Google but the results can remain the same

 http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MnHYrvR

i try this wan medium try other ways, the results remain the same

and for the front end I have tried, socket io inside the hook component and outside the scope, the results remain the same

http://localhost:8000/socket.io/?EIO=3&transport=polling&t=MnHYrvR

this is my code from server:

app.prepare().then(() => {
    const server    = express();
    const setServer = require('http').Server(server);
    const io        = require('socket.io')(setServer)

    server.use(bodyParser.json());
    server.use(cookieParser());

    io.on('connection', socket => {
        console.log('socket', socket);

        socket.emit('now', {
            message: 'zeit'
        })
    })


    server.use(routers)

    server.get('*', (req, res) => {
        return handle(req, res);
    });

    server.use( (err, req, res, next) => {
        console.log(err)
        if(err.name === 'Error'){
            res.status(401).send({
                title: 'error',
                detail: 'Unauthorized Access!'
            })
        }
    })

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://heroku:${port}`)
    })
})
.catch(ex => {
    console.error(ex.stack);
    process.exit(1);
});

from front end:

//at the top of function
const io = require('socket.io-client');
const socket = io.connect('http://localhost:8000');
console.log('socket', socket);

//in use effect
useEffect(() =>{
        socket.on('now', message => {
            console.log('message', meesage);
        })
    })

Please help

Share Improve this question asked Aug 2, 2019 at 9:11 Heru WijayantoHeru Wijayanto 4693 gold badges5 silver badges19 bronze badges 3
  • try useeffect with empty dep [], as your code right now it makes connection on every render – Dennis Vash Commented Aug 2, 2019 at 9:13
  • still get the same results.. i dont know why – Heru Wijayanto Commented Aug 2, 2019 at 9:17
  • What is the exact error and/or warning that you're seeing? – goto Commented Aug 2, 2019 at 10:55
Add a comment  | 

2 Answers 2

Reset to default 13

Although I am not using Next.js, I have a similar setup with Express.js that might help you with your problem...

On my Node.js side I have the following setup:

const app = require('express')()
const server = require('http').createServer(app)
const io = require('socket.io')(server)

// ...

io.sockets.on('connection', () => {
  console.log(`Client with ID of ${socket.id} connected!`)

  io.sockets.emit('SOME_EVENT', 'HelloWorld')
})

Then, my frontend with React looks like this:

import React from 'react'
import io from 'socket.io-client'

function useSocket(url) {
  const [socket, setSocket] = useState(null)

  useEffect(() => {
    const socketIo = io(url)

    setSocket(socketIo)

    function cleanup() {
      socketIo.disconnect()
    }
    return cleanup

    // should only run once and not on every re-render,
    // so pass an empty array
  }, [])

  return socket
}

function App() {
  const socket = useSocket('http://127.0.0.1:9080')

  useEffect(() => {
    function handleEvent(payload) {
      console.log(payload) 
      // HelloWorld
    }
    if (socket) {
      socket.on('SOME_EVENT', handleEvent)
    }
  }, [socket])

  return (...)
}

Also, one common error that I am seeing when working with socket.io is the following:

Cross-Origin Request Blocked: The Same Origin Policy disallows 
reading the remote resource at 
http://127.0.0.1:9080/socket.io/?EIO=3&transport=polling&t=MnH-W4S.
(Reason: CORS request did not succeed).

This is due an incorrect URL that's provided as a parameter in the socket manager creation process:

const socket = io('http://localhost');

So just double check that the address you're providing is correct. If you're serving your application on now and accessing it through a now.sh URL, but providing http://localhost as your URL parameter, then it won't work.

(I realise that this is an old/stale question, but in the spirit of "The Wisdom of the Ancients".)

I came across this question because I had the exact same problem. I realised that I was using the wrong server to listen with. Instead of Express, you should use the HTTP module.

    const setServer = require('http').Server(server);
    const io        = require('socket.io')(setServer)

So, this part...

    server.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://heroku:${port}`)
    })

...should become:

    setServer.listen(port, err => {
        if (err) throw err;
        console.log(`> Ready on http://heroku:${port}`)
    })
发布评论

评论列表(0)

  1. 暂无评论