Last active
July 8, 2016 11:30
-
-
Save bucho666/2bd76b51c230b7e5cc555a43d5c67d27 to your computer and use it in GitHub Desktop.
socket.io を使用したchat サンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
let socket = io.connect(), | |
input_message = $('#input_message'); | |
socket.on('connect', function() { | |
add_message('connect success'); | |
}); | |
socket.on('chat_message', function(message) { | |
add_message(message); | |
}); | |
input_message.on('keydown', function(event) { | |
if (event.which != 13) return; | |
let message = $(this).val(); | |
if (message == '') return; | |
socket.emit('chat_message', message); | |
$(this).val('').focus(); | |
}); | |
let add_message = function(message) { | |
if (message == '') return; | |
let p = $('<p>').text(message).hide(); | |
input_message.after(p); | |
p.show('fast'); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="ja"> | |
<head> | |
<meta charset="utf-8"> | |
<title>socket.io chat</title> | |
</head> | |
<body> | |
<input type="text" id="input_message" autocomplete="off"> | |
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> | |
<script src="/socket.io/socket.io.js"></script> | |
<script src="client.js"></script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
var express = require('express'), | |
app = express().use(express.static('./')), | |
socket = require('socket.io')(app.listen(8888)); | |
socket.on('connection', function(new_socket) { | |
new_socket.on('chat_message', function(message) { | |
socket.sockets.emit('chat_message', message); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment