Skip to content

Instantly share code, notes, and snippets.

@bucho666
Last active July 8, 2016 11:30
Show Gist options
  • Save bucho666/2bd76b51c230b7e5cc555a43d5c67d27 to your computer and use it in GitHub Desktop.
Save bucho666/2bd76b51c230b7e5cc555a43d5c67d27 to your computer and use it in GitHub Desktop.
socket.io を使用したchat サンプル
'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');
}
<!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>
'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