마스터욱
Toggle navigation
  • 회원가입 | 정보찾기
ICON NAVIGATION
정보수정 쪽지함 주변맛집 익명채팅
공지사항 채팅 개발문의 방명록
  • MAIN NAVIGATION
  • 메인
  • 마스터욱 공간
    • 마스터욱 소개
    • 개발 리스트
    • 공지사항
    • 방명록
  • 마스터욱 외부자료
    • 네이버
    • 티스토리
    • 깃허브(github)
  • 개인 프로젝트
    • 랜덤 이성 채팅
    • Auto 크롤링
    • Javascript 카카오 채팅
    • 파이썬 뉴스매매
    • C# 키움 주식 자동매매
    • C# 키움 주식 패턴 분석
    • PHP 욱보드
    • 업비트 자동매매 개발
    • 업비트 자동매매 일지
  • 개발 의뢰
    • 개발 문의
    • 개발 견적
    • 개발 피드백
    • FAQ
  • 개발 경험 Tip
    • PHP
    • JSP
    • HTML
    • Javascript
    • Android
    • C#
    • MySQL
    • Linux
    • Python
    • NodeJS
    • React
    • Vue.js
    • Flutter
    • 정규식
    • 기타
  • 커뮤니티
    • 자유게시판
    • 추천사이트
    • 영화
    • 여행
    • 유머
    • Overseas News
  • 맛집&즐길 거리 탐방
    • 맛집 정보
    • 즐길 거리 정보
    • 내 주위 맛집&즐길 거리
  • 공유 사진
    • 음식
    • 여행
    • 캐릭터
    • 배경
    • 기타
    • 이모티콘
    • 일러스트
  • 놀이터
    • 블록뽀시기
    • 트레이딩뷰
    • 로또 시뮬레이션
    • 쳇쳇 익명 채팅
    • 랜덤 이성 채팅
    • AI 채팅
    • 미니 채팅
    • 바이너리 테스트
    • 마번호 생성기
    • 바카라 시뮬레이션
    • 홀짝점수 테스트
    • 로또 분석기
SITE STATISTICS
  • - 명 현재 접속자
  • 1,874 명 오늘 방문자
  • 2,310 명 어제 방문자
  • 5,192 명 최대 방문자
  • 687,447 명 전체 방문자
  • 2,569 개 전체 게시물
  • 496 개 전체 댓글수
Facebook Twitter GooglePlus KakaoStory NaverBand
  1. 홈
  2. NodeJS
목록으로

socket.io 로 구현한 간단한 채팅 서버 소스코드

마스터욱 0 133 0 0 2022-12-04 23:51:40
/* Chat.js */

// 앱 실행명령어(백그라운드에서 실행)
// # node index.js > /dev/null &

// Dependencies
const fs = require('fs');
const http = require('http');
const https = require('https');
const express = require('express');

const app = express();

// letsencrypt 인증서 경로
const lets_path = '/etc/letsencrypt/live/도메인/';
const privateKey = fs.readFileSync(lets_path + 'privkey.pem', 'utf8');
const certificate = fs.readFileSync(lets_path + 'cert.pem', 'utf8');
const ca = fs.readFileSync(lets_path + 'chain.pem', 'utf8');

const credentials = {
key: privateKey,
cert: certificate,
ca: ca
};

app.use((req, res) => {
res.send('욱이의 채팅서버입니다. 웹으로는 들어오지 마세용~ (o^3^)o~');
});

// Starting both http & https servers
const httpServer = http.createServer(app);
const httpsServer = https.createServer(credentials, app);

////////////////////////////// 채팅 클래스
class Chat
{
constructor(arg = {}){
this.protocol = arg['protocol'];
this.server = arg['server'];
this.port = arg['port'];
this.usrcnt = 0;
this.io = null;
}

init(){
this.server.listen(this.port, () => {
console.log(this.protocol + ' Server running on port ' + this.port);
});

this.io = require('socket.io')(this.server);
this.io.on('connection', (socket) => {
console.log('user connected');
//메세지 수신시
socket.on('send', (res) => {
//socket.emit('recv', data); //메세지를 발송한 본인에게만
console.log('recv ok');
this.io.emit('recv', res); //전체 커넥션 유저들에게
});

//메세지 삭제시
socket.on('msg_del', (msg_idx) => {
this.io.emit('msg_del_result', msg_idx); //전체 커넥션 유저들에게
});

//브라우저 접속시
this.usrcnt++;
console.log('connect', this.usrcnt);
this.io.emit('usr_cnt_'+this.protocol, this.usrcnt);

//브라우저를 떠날때 실행됨
socket.on('disconnect', () => {
this.usrcnt--;
console.log('disconnect', this.usrcnt);
this.io.emit('usr_cnt_'+this.protocol, this.usrcnt);
});
});
}
}

var httpChat  = new Chat({'protocol':'http', 'server':httpServer, 'port':'39'});
httpChat.init();

var httpsChat = new Chat({'protocol':'https', 'server':httpsServer, 'port':'443'});
httpsChat.init();

================================================================================

http랑 https 두개의 프로토콜이 모두 사용되어지는 채팅 클래스 소스코드 입니다.
0
0

목록

Facebook Twitter GooglePlus KakaoStory NaverBand
0 Comments

비밀번호 확인

확인
댓글은 자신을 나타내는 '얼굴'입니다. *^^*
등록
자동등록방지 숫자를 순서대로 입력하세요.

댓글수정


글쓰기
검색
번호 제목 이름 날짜 조회
  • 21
    우분투 DB&Home 폴더 자동백업 프로그램
    마스터욱
    조회수 184   25-07-29 05:47
    마스터욱
    25-07-29 05:47
    184
  • 20
    pm2 로그파일 관리
    마스터욱
    조회수 168   24-10-27 04:38
    마스터욱
    24-10-27 04:38
    168
  • 19
    CSR(client side rendering) 사이트 크롤링 하기
    마스터욱
    조회수 131   24-06-10 16:59
    마스터욱
    24-06-10 16:59
    131
  • 18
    변수값이 변경되었을 경우, 특정 함수 실행 시키기(예제)
    마스터욱
    조회수 155   23-06-30 17:25
    마스터욱
    23-06-30 17:25
    155
  • 17
    socket.io 로 구현한 간단한 채팅 서버 소스코드
    마스터욱
    조회수 134   22-12-04 23:51
    마스터욱
    22-12-04 23:51
    134
  • 16
    PM2를 활용한 Node.js 무중단 서비스하기
    마스터욱
    조회수 134   22-08-10 00:45
    마스터욱
    22-08-10 00:45
    134
  • 15
    nodejs - js파일 include(import)
    마스터욱
    조회수 167   21-09-29 04:25
    마스터욱
    21-09-29 04:25
    167
  • 14
    (에러)Allocation failed - JavaScript heap out of memory
    마스터욱
    조회수 189   21-08-01 20:37
    마스터욱
    21-08-01 20:37
    189
  • 13
    node js 에러가 발생할 경우
    마스터욱
    조회수 149   20-08-28 10:14
    마스터욱
    20-08-28 10:14
    149
  • 12
    리눅스 서버에서 실행중인 node js 프로세스 확인 및 끄기
    마스터욱
    조회수 181   20-08-05 12:38
    마스터욱
    20-08-05 12:38
    181
  • 11
    4시간동안 삽질한 개행(\n) 처리 문제
    마스터욱
    조회수 124   20-03-31 13:51
    마스터욱
    20-03-31 13:51
    124
  • 10
    카페24 node.js 서버로 채팅서버 이전작업
    마스터욱
    조회수 299   20-03-10 12:09
    마스터욱
    20-03-10 12:09
    299
  • 9
    중간점검 완성된 소스
    마스터욱
    조회수 148   20-03-02 03:21
    마스터욱
    20-03-02 03:21
    148
  • 8
    date-utils 설치
    마스터욱
    조회수 162   20-03-02 03:01
    마스터욱
    20-03-02 03:01
    162
  • 7
    crypto-js 설치
    마스터욱
    조회수 142   20-03-02 00:04
    마스터욱
    20-03-02 00:04
    142
  • 6
    Node.js & MySQL 연동
    마스터욱
    조회수 156   20-03-01 02:38
    마스터욱
    20-03-01 02:38
    156
  • 5
    socket.js 코드작성
    마스터욱
    조회수 153   20-03-01 01:02
    마스터욱
    20-03-01 01:02
    153
  • 4
    socket.io 설치
    마스터욱
    조회수 173   20-03-01 00:17
    마스터욱
    20-03-01 00:17
    173
  • 3
    로컬에 express 설치
    마스터욱
    조회수 144   20-03-01 00:03
    마스터욱
    20-03-01 00:03
    144
  • 2
    로컬에 Node.js 설치
    마스터욱
    조회수 122   20-02-29 23:50
    마스터욱
    20-02-29 23:50
    122
글쓰기
검색
  • 1
  • 2
  • 다음

Search

개인정보처리방침
마스터욱. All rights reserved.

Close

0 명 접속중
Time Loading...