socket.io

jadive study·2022년 10월 12일
0

son formatter

→ 제이슨 바꿔줌

HTTP통신

응답하는 단방향 통신

소켓통신

통신단자 두프로그램이 서로 데이터를 주고받을 수 있는 양쪽통신

전선 — 소켓 // 서버와 클라이언트 양방향 연결


socket.IO

Untitled


const socket = new WebSocket("ws://localhost:3000");

socket.addEventListener("open", () => {

// send a message to the server

socket.send(JSON.stringify({

type: "hello from client",

content: [ 3, "4" ]

}));

});

// receive a message from the server

socket.addEventListener("message", ({ data }) => {

const packet = JSON.parse(data);

switch (packet.type) {

case "hello from server":

// ...

break;

}

});

const { createServer } = require("http");
const { Server } = require("socket.io");
const httpServer = createServer();

const io = require("socket.io")(httpServer, {
  // CORS 처리
  cors: {
    origin: "http://localhost:8080",
    methods: ["GET", "POST"]
  }
});

// socket.io 연결
io.on("connection", (socket) => {
  console.log('connected socket.io', socket.id);

  socket.on('chat', msg => {
    console.log('chat', msg);
    io.emit('chat', msg);
  });
});

// http서버 실행
const port = 3010;
httpServer.listen(port);
console.log(`socket.io listening: ${port}`);

ws.on('message', (message) => { // 클라이언트로부터 메시지
      console.log(message.toString());
    });

https://medium.com/wasd/node-js와-socket-io를-이용한-채팅-구현-3-cc1112d4262c

profile
개발 메모창고

0개의 댓글