Socket.IO とは
Socket.IO は、WebSocket の双方向の非同期通信を簡単にでき、Node.js サーバーとクライアントの間のリアルタイム通信を提供するライブラリです。
インストール
npm install socket.io
Socket.IO は、WebSocket の双方向の非同期通信を簡単にでき、Node.js サーバーとクライアントの間のリアルタイム通信を提供するライブラリです。
npm install socket.io
発する、放出する
切断する
受け口、軸受け、接合部
socket.emit('イベント名', データ);
socket.on('イベント名', function(引数) {});
Express Generator を使ってアプリを作成します。
アプリの名前をここでは、「 socket 」として作成しました。
次のようにファイルを変更した後、アプリを起動します。
ブラウザを2つ起動し「 http://localhost:3090/ 」を開きます。メッセージを送信し2つのブラウザで送信されたテキストが表示されれば成功です。
#!/usr/bin/env node
/**
* Module dependencies.
*/
var app = require('../app');
const chat = require('../models/chat');
const debug = require('debug')('express-ws-ejs:server');
var http = require('http');
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3090');
app.set('port', port);
/**
* Create HTTP server.
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
chat(server);
/**
* Normalize a port into a number, string, or false.
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* Event listener for HTTP server "error" event.
*/
function onError(error) {
if (error.syscall !== 'listen') {
throw error;
}
var bind = typeof port === 'string'
? 'Pipe ' + port
: 'Port ' + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case 'EACCES':
console.error(bind + ' requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error(bind + ' is already in use');
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === 'string'
? 'pipe ' + addr
: 'port ' + addr.port;
debug('Listening on ' + bind);
}
const socketio = require('socket.io');
function chat(server) {
const io = socketio(server);
io.on('connection', function(socket) {
console.log('connection successful');
socket.on('chat', function(msg) { // 'chat' というイベント名は任意で命名します
io.emit('chat', msg);
});
socket.on("disconnect", function() {
});
});
};
module.exports = chat;
window.onload = function(){
const socket = io('http://localhost:3090');
const form = document.getElementById("chatForm");
form.addEventListener("submit", function(e){
const m = document.getElementById("m");
console.log(m.value);
socket.emit('chat', m.value);
e.preventDefault();
});
socket.on('chat', function(msg) {
const box = document.getElementById("messages");
box.innerHTML += `<li>${msg}</li>`;
});
}
<html>
<head>
<title>socket.io</title>
<script src="/socket.io/socket.io.js"></script>
<script src="javascripts/socket.js"></script>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1>Socket.io</h1>
<ul id="messages"></ul>
<form id="chatForm">
<input id="m" autocomplete="off">
<button type="submit">Send</button>
</form>
</body>
</html>