간단한 노드 채팅 예제입니다
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
게시글 목록
| 번호 | 제목 |
|---|---|
| 17591 |
node.js
노드로 멀티스레드 기능 구현하기
2
|
| 17590 | |
| 17589 |
PHP
PHP로 인쇄명령주기
1
|
| 17588 |
JavaScript
Javascript로 JSON데이터를 보기좋게 만들기
|
| 17587 | |
| 17584 | |
| 17583 |
MySQL
MySQL과 PostgreSQL의 우단점
|
| 17582 |
MySQL
프로시저 cursor 사용 예
|
| 17581 |
JavaScript
바닐라 ajax 파일업로드 예제
|
| 17579 | |
| 17577 | |
| 17575 | |
| 17574 | |
| 17573 | |
| 17572 | |
| 17569 | |
| 17564 | |
| 17560 | |
| 17559 |
MySQL
프로시저 기본편
|
| 17555 | |
| 17554 | |
| 17553 | |
| 17552 | |
| 17549 | |
| 17548 | |
| 17547 | |
| 17542 | |
| 17533 | |
| 17531 | |
| 17524 |
댓글 작성
댓글을 작성하시려면 로그인이 필요합니다.
로그인하기