공부/TIL

[Node.js] Socket.io를 이용한 TCP/IP chat program 구현

Ail_ 2023. 7. 15. 04:03

저번 포스팅에 이어 Socket.io를 이용해 간단한 TCP chat program을 구현해보겠다.

 

우선 socket.io를 설치한다.

npm i socket.io
// 클라이언트용
npm i socket.io-client

 

나는 클라이언트쪽도 구현해야 하기 때문에 socket.io-client도 설치했다.

파일 구조는 저번 포스팅과 동일하다.

 

server.js의 코드는 다음과 같다 :

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

io.on('connection', client => {
    console.log('클라이언트와 연결되었습니다.')

    // 클라이언트로부터 데이터를 받았을 때 처리하는 부분
    client.on('event', data => { 
        console.log('클라이언트로부터 메세지를 수신했습니다: ', data.toString().trim())
    })

    // 클라이언트와 연결이 끊겼을 때 처리하는 부분
    client.on('disconnect', () => {
        console.log('클라이언트와의 통신이 종료되었습니다')
    })

    // 클라이언트와의 연결에서 발생한 에러를 처리하는 부분
    client.on('error', error => {
        console.error('클라이언트 에러가 발생했습니다: ', error)
    })
})

// 서버에서 발견한 에러를 처리하는 부분
io.on('error', error => {
    console.error('서버에서 에러가 발생했습니다: ', error)
})

// 서버를 특정 포트에서 대기 시킴
server.listen(3000)

코드를 작성하다 보니, 클라이언트와 서버에서 발생한 에러는 각각 처리해주어야 한다는 깨달음을 얻었다. 오랜만에 백엔드를 공부해보니 까먹은 게 한두개가 아니다...

 

client.js의 코드는 다음과 같다 :

const io = require('socket.io-client')
const readline = require('readline')

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

socket.on('connect', () => {
  console.log('서버에 연결되었습니다.')

  // 사용자 입력을 받기 위한 인터페이스 설정
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
  })

  // 사용자 입력을 받아서 서버로 전송
  rl.on('line', input => {
    try {
        socket.emit('event', input)
    } catch (error) {
        console.log('클라이언트 에러가 발생했습니다: ', error)
    }
  })

  // 서버로부터 데이터 수신 시 처리하는 부분
  socket.on('event', data => {
    console.log('서버로부터 메시지를 받았습니다:', data.toString().trim())
  })

  // 서버와의 연결이 끊겼을 때 처리하는 부분
  socket.on('disconnect', () => {
    console.log('서버와의 연결이 종료되었습니다.')
    rl.close() // 사용자 입력 인터페이스를 닫음
  })

  // 서버와의 연결에서 발생한 에러를 처리하는 부분
  socket.on('error', error => {
    console.error('서버에서 에러가 발생했습니다:', error)
  })
})

클라이언트 자체적으로 발생한 에러 처리는 try-catch를 이용한다.

 

결과물

 

참고
https://www.npmjs.com/package/socket.io
그리고 chatgpt