Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

nextjs socket.io

/*
Install SocketIO for Creating Server
npm i socket.io

Install SocketIO-Client for Creating Client 
npm i socket.io-client
*/

// Socket Server
// pages/api/socket.js ------------------------------
import { Server } from 'socket.io'

const SocketHandler = (req, res) => {
  if (res.socket.server.io) {
    console.log('Socket is already running')
  } else {
    console.log('Socket is initializing')
    const io = new Server(res.socket.server)
    res.socket.server.io = io

    io.on('connection', socket => {
      socket.on('input-change', msg => {
        socket.broadcast.emit('update-input', msg)
      })
    })
  }
  res.end()
}

export default SocketHandler
// --------------------------------------------------

// Socket Client
// pages/home.js -----------------------------------
import { useEffect, useState } from 'react'
import io from 'socket.io-client'
let socket;

const Home = () => {
  const [input, setInput] = useState('')

  useEffect(() => {
      socketInitializer();
      return () => {
        console.log("This will be logged on unmount");
      }
    })

  const socketInitializer = async () => {
    await fetch('/api/socket');
    socket = io()

    socket.on('connect', () => {
      console.log('connected')
    })

    socket.on('update-input', msg => {
      setInput(msg)
    })
  }

  const onChangeHandler = (e) => {
    setInput(e.target.value)
    socket.emit('input-change', e.target.value)
  }

  return (
    <input
      placeholder="Type something"
      value={input}
      onChange={onChangeHandler}
    />
  )
}

export default Home;
// ----------------------------------------------
Comment

socket.io node

/*The following example attaches socket.io to a plain Node.JS HTTP server listening on port 3000.*/

const server = require('http').createServer();
const io = require('socket.io')(server);
io.on('connection', client => {
  client.on('event', data => { /* … */ });
  client.on('disconnect', () => { /* … */ });
});
server.listen(3000);



//Standalone

const io = require('socket.io')();
io.on('connection', client => { ... });
io.listen(3000);
//Module syntax
import { Server } from "socket.io";
const io = new Server(server);
io.listen(3000);
                               
                               
                               
//In conjunction with Express
//Starting with 3.0, express applications have become request handler functions that you pass to http or http Server instances. You need to pass the Server to socket.io, and not the express application function. Also make sure to call .listen on the server, not the app.

const app = require('express')();
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
                               
                               
//In conjunction with Koa
//Like Express.JS, Koa works by exposing an application as a request handler function, but only by calling the callback method.

const app = require('koa')();
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
io.on('connection', () => { /* … */ });
server.listen(3000);
                               
                               
                               
//In conjunction with Fastify
//To integrate Socket.io in your Fastify application you just need to register fastify-socket.io plugin. It will create a decorator called io.

const app = require('fastify')();
app.register(require('fastify-socket.io'));
app.io.on('connection', () => { /* … */ });
app.listen(3000);
     
Comment

PREVIOUS NEXT
Code Example
Javascript :: react native portrait only 
Javascript :: how to define emojis from your server in discord.js 
Javascript :: charcodeat vs codepointat 
Javascript :: de structuring value from object ES6 and javascript 
Javascript :: fetch json file 
Javascript :: javascript print all items in array 
Javascript :: sort array of objects javascript by value 
Javascript :: js redirect to url 
Javascript :: javascript redirect browser 
Javascript :: function redirect javascript 
Javascript :: click listener on by class name in javascript 
Javascript :: while loop countdown javascript 
Javascript :: regex check from a-z 0-9 
Javascript :: Password checking regex 
Javascript :: reactjs router link props 
Javascript :: jquery enable disable textbox 
Javascript :: js email regex 
Javascript :: js check which number is larger 
Javascript :: reload datatable ajax 
Javascript :: local storage angular 
Javascript :: falsy values in array 
Javascript :: js alert 
Javascript :: js string contains substring ignore case 
Javascript :: get nearby store by latitude and longitude from my latitude and long node js 
Javascript :: find element in array javascript 
Javascript :: useffect compare previous value to current 
Javascript :: focus js 
Javascript :: port 3000 is already in use nodemon app crashed 
Javascript :: how to find the last item in a javascript object 
Javascript :: vuejs scrollBehavior 
ADD CONTENT
Topic
Content
Source link
Name
8+2 =