간단한 채팅
간단한 노드 채팅 예제입니다
1. 노드설치 후, 서버 js 실행
// server.js
var express = require('express');
var app = express();
var http = require('http').Server(app); //1
var io = require('socket.io')(http); //1
app.get('/',function(req, res){ //2
res.sendFile(__dirname + '/client.html');
});
var count=1;
io.on('connection', function(socket){ //3
console.log('user connected: ', socket.id); //3-1
var name = "user" + count++; //3-1
io.to(socket.id).emit('change name',name); //3-1
socket.on('disconnect', function(){ //3-2
console.log('user disconnected: ', socket.id);
});
socket.on('send message', function(name,text){ //3-3
var msg = name + ' : ' + text;
console.log(msg);
io.emit('receive message', msg);
});
});
http.listen(3000, function(){ //4
console.log('server on!');
});
2. 메세지 입력 화면
// client.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Chat</title>
<style>
.chat_log{ width: 95%; height: 200px; }
.name{ width: 10%; }
.message{ width: 70%; }
.chat{ width: 10%; }
</style>
</head>
<body>
<div>
<textarea id="chatLog" class="chat_log" readonly></textarea>
</div>
<form id="chat">
<input id="name" class="name" type="text" readonly>
<input id="message" class="message" type="text">
<input type="submit" class="chat" value="chat"/>
</form>
<div id="box" class="box">
<script src="/socket.io/socket.io.js"></script> <!-- 1 -->
<script src="//code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io(); //1
$('#chat').on('submit', function(e){ //2
socket.emit('send message', $('#name').val(), $('#message').val());
$('#message').val('');
$('#message').focus();
e.preventDefault();
});
socket.on('receive message', function(msg){ //3
$('#chatLog').append(msg+'\n');
$('#chatLog').scrollTop($('#chatLog')[0].scrollHeight);
});
socket.on('change name', function(name){ //4
$('#name').val(name);
});
</script>
</body>
</html>
상세설명
https://onlyfor-me-blog.tistory.com/99
게시판 목록
개발자팁
질문은 QA에서 해주시기 바랍니다.
| 번호 | 분류 | 제목 | 글쓴이 | 날짜 | 조회 |
|---|---|---|---|---|---|
| 5006 | 기타 | 5년 전 | 1922 | ||
| 5005 | 기타 | 5년 전 | 2021 | ||
| 5004 | 기타 | 5년 전 | 2136 | ||
| 5003 | 기타 | 5년 전 | 2813 | ||
| 5002 | 기타 | 5년 전 | 2388 | ||
| 5001 | 기타 | 5년 전 | 2724 | ||
| 5000 | 기타 | 5년 전 | 4766 | ||
| 4999 | 기타 | 5년 전 | 2028 | ||
| 4998 | 기타 | 5년 전 | 2693 | ||
| 4997 | 기타 | 5년 전 | 2743 | ||
| 4996 | 기타 | 5년 전 | 2667 | ||
| 4995 | 기타 | 5년 전 | 2912 | ||
| 4994 | 기타 | 5년 전 | 2166 | ||
| 4993 | 기타 | 5년 전 | 2041 | ||
| 4992 | 기타 | 5년 전 | 1968 | ||
| 4991 | 기타 | 5년 전 | 1982 | ||
| 4990 | 기타 | 5년 전 | 2043 | ||
| 4989 | 기타 | 5년 전 | 2365 | ||
| 4988 | 기타 | 5년 전 | 2055 | ||
| 4987 | 기타 | 5년 전 | 2328 | ||
| 4986 | 기타 | 5년 전 | 2800 | ||
| 4985 | 웹서버 | 5년 전 | 4947 | ||
| 4984 | OS | 5년 전 | 3009 | ||
| 4983 | MySQL | 5년 전 | 2894 | ||
| 4982 | 기타 | 5년 전 | 2013 | ||
| 4981 | PHP | 5년 전 | 2656 | ||
| 4980 | 기타 | 5년 전 | 8975 | ||
| 4979 | 웹서버 | 5년 전 | 3077 | ||
| 4978 | 기타 | 5년 전 | 2051 | ||
| 4977 | PHP | 5년 전 | 3515 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기