socket 기능

npm i socket.io --s

chat01.js

var http=require('http')
, fs=require('fs')
, path=require('path')
, socketio=require('socket.io')
, static = require('serve-static')
, express = require('express');

var app = express();

app.get('/',function(req,res){
    fs.readFile('../public/chat03.html','utf8',function(err,data){
        if(err) throw err;
        res.send(data);
    });
})


//미들웨어
app.use('/',static(path.join(__dirname,'../public')));


//웹서버 생성 후 가동
var server = http.createServer(app).listen(3333,function(){
    console.log('http://localhost:3333');
})

//소켓서버 생성
var io = socketio.listen(server);
var uid=0;
//io.sockets객체에 connection 연결 이벤트를 붙인다.
io.sockets.on('connection',function(socket){
    console.log("connection 이벤트 핸들러 >>> 클라이언트가 접속");
    uid=socket.id;
    console.log('uid=='+uid);
    
    
    socket.on('hello',function(data){
        console.log("클라이언트가 보낸 데이터>>"+data);
        
        /*
        [1] public 통신 (나를 포함한 모든 접속자들에게 메시지를 보낸다.)
            io.sockets.emit('sendAll', data)
        [2] broadcast 통신 (나를 제외한 모든 접속자들에게 메시지를 보낸다.)
            socket.broadcast속성을 이용
            socket.broadcast.emit('sendBroad',data)
        [3] private 통신 (특정접속자에게만 메시지를 보낸다.)
            socket.id를 사용하여 특정인에게만 메시지를 보낸다.
            io.sockets.to(socket.id).emit('sendOne',data)
        [4] 특정 방에 입장한 접속자들에게 메시지를 보내는 경우 
            io.sockets.in('방이름') 함수를 이용해서 emit 한다.
        */
           
           //io.sockets.emit('sendAll',data);
           
           //socket.broadcast.emit('sendBroad',data);
           
           //io.sockets.to(uid).emit('sendOne',data)
    })
})

chat01.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <!-- Latest compiled and minified CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

    <!-- jQuery library -->
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <!-- Popper JS -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

    <!-- Latest compiled JavaScript -->
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

    <!-- Socket 통신-->
    <script src="/socket.io/socket.io.js"></script>
    <script>
        var socket;
        
        $(function(){
            //소켓을 생성
            socket=io.connect();
            
            //텍스트 박스에 사용자가 입력한 값을 받아서 서버쪽에 해당 값을 전송
            $('#btn').click(function(){
                var mymsg=$('#txt').val();
                send(mymsg);
            })

            //키보드로 입력하고 엔터를 쳤을 때 서버쪽에 메시지를 전송
            $('#txt').keyup(function(e){
                console.log(e.keyCode); //enter는 13이다.
                if(e.keyCode==13){
                    var mymsg=$('#txt').val();
                    send(mymsg);
                }
            })

            socket.on('sendOne',function(data){
                //alert(data);
                $('#msg').append(data+"<br>").css('color','green');
            })



        })//$()end------------------

        function send(mymsg){
            socket.emit('hello',mymsg);
            //소켓을 통해 hello라는 이벤트를 발생시킨다.
            $('#txt').val('').focus();
        }
    </script>
    <style>
        div#msg{
            height:500px;
            overflow:auto;
            border:1px solid salmon;
        }

    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-center m-5">Simple Chat - private</h1>
        <div class="row">
            <div class="col-md-8 offset-md-2">
                <input type="text" id="txt" class="form-control" placeholder="Message">
                <button id="btn" class="btn btn-primary">Echo</button>
            </div>
        </div>
        <div class="row m-3">
            <div class="col-md-8 offset-md-2">
                <div id="msg"></div>
            </div>
        </div>
    </div>
</body>
</html>

mychat 방생성

mychat.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Swan's Chat</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
	href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link
	href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.3.0/css/font-awesome.min.css"
	rel="stylesheet" type="text/css">
<style type="text/css">
		.discussion {
		  	list-style: none;
		  	background: #ededed;
		  	margin: 0;
		  	padding: 0 0 50px 0;
		}
		
		.discussion li {
		  	padding: 0.5em;
		  	overflow: hidden;
		  	display: flex;
		}
		
		.discussion .avatar {
		  	width: 40px;
		  	position: relative;
		}
		
		.discussion .avatar img {
		  	display: block;
		  	width: 100%;
		}
		
		.other .avatar:after {
		  	content: "";
		  	position: absolute;
		  	top: 0;
		  	right: 0;
		  	width: 0;
		  	height: 0;
		  	border: 5px solid white;
		  	border-left-color: transparent;
		  	border-bottom-color: transparent;
		}
		
		.self {
		  	justify-content: flex-end;
		  	align-items: flex-end;
		}
		
		.self .messages {
		  	order: 1;
		  	border-bottom-right-radius: 0;
		}
		
		.self .avatar {
		  	order: 2;
		}
		
		.self .avatar:after {
		  	content: "";
		  	position: absolute;
		  	bottom: 0;
		  	left: 0;
		  	width: 0;
		  	height: 0;
		  	border: 5px solid white;
		  	border-right-color: transparent;
		  	border-top-color: transparent;
		  	box-shadow: 1px 1px 2px rgba(0, 0, 0, 0.2);
		}
		
		.messages {
		  	background: white;
		  	padding: 10px;
		  	border-radius: 2px;
		  	box-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
		}
		
		.messages p {
		  	font-size: 0.8em;
		  	margin: 0 0 0.2em 0;
		}
		
		.messages time {
		  	font-size: 0.7em;
		  	color: #ccc;
		}

</style>	
	
<script
	src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script
	src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<!-- socket.io참조-------------------------------------------------  -->
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<!-- -------------------------------------------------------------- -->
<script type="text/javascript">
	var socket;
	var mynick; // 내 닉네임을 보관할 변수
	$(function(){
		socket=io.connect();
		disableChat();//방에 입자하기 전에는 채팅을 비활성화
		$('#btnRoomMake').click(function(){
			//alert('a');
			//방 이름 얻어오기
			var roomName=$('#roomname').val();
			//닉네임 얻어오기
			var nickName=$('#nickname').val();
			
			var bool = check(roomName,nickName);
			if(bool){
				//서버에 데이터를 보내기
				//데이터를 json형태로 만들자
				var str={
					cmd:'create',
					roomName: roomName,
					nickName: nickName
				};
				socket.emit('room',str);
				//room이벤트를 발생시켜 데이터를 보내자.
			}
		});

		socket.on('response',function(data){
			console.dir(data);
			showStatus("응답 데이터를 받았습니다: "+data.cmd+", "+data.code+", "+data.message);
		})
		
	})//$()end ---

	function showStatus(str){
		$('#status').html(str)
					.css('color','tomato')
					.css('font-weight','bold');
	}

	//채팅 비활성화 => 방 퇴장시
	function disableChat(){
		$('#inputMsg').attr('readonly',true);
		$('#taMsg').attr('readonly',true);
	}

	//채팅 활성화 => 방 입장시
	function enableChat(){
		$('#inputMsg').attr('readonly',false);
		$('#taMsg').attr('readonly',false);
	}

	//유효성 체크하는 함수
	function check(roomName, nickName){
		if(!roomName){
			alert("방 이름을 입력하세요");
			$('#roomname').focus();
			return false;
		}
		if(!nickName){
			alert("닉네임을 입력하세요");
			$('#nickname').focus();
			return false;
		}
		return true;
	}

</script>	

</head>
<body>
	<div class="container">
		<div class="section">
			<div class="row">
				<div class="col-md-12">
					<h1 class="text-center text-primary">
						<a><i class="fa fa-fw fa-heart-o fa-lg hub"></i></a>Swan's
						Chatting<a><i class="fa fa-fw fa-heart-o fa-lg hub"></i></a>
					</h1>
					

					<div class="panel-group" style="margin-top: 30px;">


						<div class="panel panel-danger col-md-7" id="roommake"
							style="height: 250px;">
							<div class="panel-heading">
								<a style="color: #d9534f;"><i
									class="fa fa-2x fa-fw hub fa-home"></i></a>방만들기
							</div>
							<div class="panel-body">
								<div class="row">
									<label class="col-md-3" for="roomname">방이름 :</label>
									<div class="col-md-9">
										<input id="roomname" type="text" class="form-control"
											placeholder="방이름">
									</div>
								</div>
								<div class="row" style="margin-top: 8px; margin-bottom: 10px">
									<label class="col-md-3" for="nickname">닉네임 :</label>
									<div class="col-md-9">
										<input id="nickname" type="text" class="form-control"
											placeholder="닉네임">
									</div>
								</div>
								<div class="row">
									<div class="col-md-12 text-right">

										<input id="btnRoomMake" type="button" value="방만들기"
											class="btn btn-primary">
										<button class="btn btn-warning" id="btnRename">방이름 변경</button>
										<button class="btn btn-danger" id="btnRemove">방 삭제</button>
										<button class="btn btn-info" id="btnEnter">방에 입장</button>
										<button class="btn btn-success" id="btnExit">방나가기</button>
									</div>
								</div>
							</div>
						</div>

						<div class="panel panel-warning col-md-4" id="room"
							style="height: 250px; overflow: auto; margin-left: 10px">
							<div class="panel-heading">
								<a style="color: #d9534f;"><i class="fa fa-2x fa-fw fa-list"></i></a>개설된
								방목록
								
							</div>
							<div class="panel-body">
								<div id="roomlist">
									<!-- <ol >
										<li>One</li>
										<li>Two</li>
										<li>Three</li>
									</ol> -->
								</div>
							</div>
						</div>

						<div class="panel panel-info col-md-11" id="chatroom"
							style="margin-top: 13px">
							<div class="panel-heading">
								<a><i class="fa fa-3x fa-fw fa-comments-o"></i></a>:::Chat:::
								<div id="myinfo"></div>
								<div id="status"></div>
							</div>
							<div class="panel-body">
								<div id="chatmsg" class="col-md-10 col-md-offset-1">
									<div class="row">
										<label class="col-md-3 text-right" for="nickname">메시지
											:</label>
										<div class="col-md-9">
											<input id="inputMsg" type="text" class="form-control"
												placeholder="메시지를 입력하세요">
										</div>
									</div>
									<div class="row" style="margin-top: 10px">
										<div class="col-md-3" id="ulist">
										</div>
										<div class="col-md-9">
											<div id="taMsg"
											 class="discussion" style="width:100%;height:400px;overflow: auto" readonly class="form-control"></div>
										</div>
										
									</div>
								</div>
							</div>
						</div>
					</div>
					
					

				</div>
			</div>
		</div>
	</div>
</body>
</html>

mychat.js

var http=require('http')
, fs=require('fs')
, path=require('path')
, socketio=require('socket.io')
, static = require('serve-static')
, express = require('express');

var app = express();
//미들웨어
app.use('/',static(path.join(__dirname,'public')));


app.get('/',function(req,res){
    fs.readFile('./public/mychat.html','utf8',function(err,data){
        if(err) throw err;
        res.send(data);
    });
})

//웹서버 생성 후 가동
var server = http.createServer(app).listen(3333,function(){
    console.log('http://localhost:3333');
})

var io = socketio.listen(server);
var users= [];

io.sockets.on('connection',function(socket){
    console.log("클이 접속함...");
    socket.on('room',function(data){
        //console.dir(data);
        if(data.cmd=='create'){//방만들기라면
            var isExist=false;
            if(isExist){
                //생성한 방이 이미 존재하는 경우
                
            }else{
                //새로 만드는 방인 경우
                //socket.join('방이름') ==> 방생성
                socket.join(data.roomName);
                users.push({
                    roomName:data.roomName,
                    bangjang:data.nickName,
                    ulist:[data.nickNamee] //방에 입장한 사람들 목록
                })
                //console.log('create users[0].ulist: '+users[0].ulist)
                sendResponse(socket,'room','100',
                '['+data.roomName+'] 방이 생성 됐어요 방장: ['+data.nickName+']');
            }
        }//create------
    })//.on('room') end -------------
})//.on('connection') end-----------


//클에게 응답을 전송하는 함수
var sendResponse = function(socket, command, code, msg){
    //클에게 보낼 응답 데이터 만들기
    var str={cmd:command,code:code,message:msg};
    socket.emit('response',str); //클에게 응답 데이터 전송
}

 

+ Recent posts