socketio

Jaymee·2021년 9월 8일
0

인앱채팅을 구현하기 위해 공부하게 되었다.
기본적으로 http에는 stateless, connectionless 한 성격이 있다.

  • connectionless : 클라이언트와 서버와의 통신이 끝나면 연결을 끊어버린다.
  • stateless : 클라이언트와 서버와의 연결이 끊기면 상태를 유지하지 않는다.

그렇기 때문에, 클라이언트와 서버와의 연결을 지속적으로 유지하고 통신하기 위해서는 다른 프로토콜이 필요했다. 그 방법으로 socketio를 사용하고자 한다.

socketio

클라이언트와 서버간의 양방향 통신을 위해 html5 websocket 을 많이 사용하지만, 오래된 브라우저일 경우, 지원하지 않는 경우가 있다.
그래서 Node.js를 위한 강력한 Cross-platform WebSocket APISocket.io를 주로 사용한다.

$ npm install --save-dev socket.io


const express = require('express');
const socket = require('socket.io');

// App Setup
var app = express();
// Create server and listen to specific port number
var server = app.listen(4000, function(){
	console.log('Listening to requests on port 4000');
});

// Socket setup; provide server reference to work with
var io = socket(server);

// Listening to an connection event; socket parameter refers to created/particular socket
io.on('connection', function(socket){
	// Print socket id on new connection
	console.log(`made socket connection, ${socket.id}`);

	// Listen for chat message being sent from client
	socket.on('newUser1', function(data){
		// Send received chat message to all connected clients
		io.sockets.emit('updateMessage', "newUser1이 접속하였습니다.");
	});

    socket.on('disconnect', () => {
        socket.broadcast.emit('updateMessage', "newUser1이 나갔습니다. ");
        console.log(`Socket disconnected : ${socket.id}`)
    })
});

클라이언트 연결

io.on('connection', function(socket){
  
});

클라이언트가 socketio 서버에 접속하게 되면, 이벤트(connection)가 발생하는데 그때 이벤트 객체가 socket이다.

지금 연결된 클라이언트와의 interacting을 위한 객체가 socket이고, 연결되는 전체 클라이언트와의 intercting을 위한 객체가 io가 되는것이다.


클라이언트 메세지 수신

socket.on('newUser1', function(data){
    
})

현재 접속하고 있는 클라이언트객체, socket으로 부터 메세지를 받는 함수가 on 이라는 함수이다.

parameterdescription
event name클라이언트가 메시지 송신 시 지정한 이벤트 명(string)
function이벤트 핸들러. 핸들러 함수의 인자로 클라이언트가 송신한 메시지가 전달된다.

클라이언트에게 메세지 송신

io.sockets.emit('newUser1', "newUser1이 접속하였습니다.");

클라이언트 메세지를 수신할 때의 이벤트명과 송신할때의 이벤트명이 반드시 같아야 한다.

그외 함수

// 접속된 모든 클라이언트에게 메시지를 전송한다
io.emit('event_name', msg);

// 메시지를 전송한 클라이언트에게만 메시지를 전송한다
socket.emit('event_name', msg);

// 메시지를 전송한 클라이언트를 제외한 모든 클라이언트에게 메시지를 전송한다
socket.broadcast.emit('event_name', msg);

// 특정 클라이언트에게만 메시지를 전송한다
io.to(id).emit('event_name', data);
MethodDescription
io.emit접속된 모든 클라이언트에게 메시지를 전송한다.
socket.emit메시지를 전송한 클라이언트에게만 메시지를 전송한다.
socket.broadcast.emit메시지를 전송한 클라이언트를 제외한 모든 클라이언트에게 메시지를 전송한다.
io.to(id).emit특정 클라이언트에게만 메시지를 전송한다. id는 socket 객체의 id 속성값이다.

ParameterDescription
event name이벤트 명(string)
msg송신 메시지(string or object)



Room

https://poiemaweb.com/nodejs-socketio

profile
backend developer

0개의 댓글