Skip to content

Instantly share code, notes, and snippets.

@pahaz pahaz/index.html
Last active Jan 9, 2016

Embed
What would you like to do?
socket-io chat example
<!doctype html>
<html lang="en">
<head>
<title>Chat Example</title>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var socket = io.connect();
var messages = [];
function do_on_connect () {
console.log('connect!');
}
function do_on_message_from_server (msg) {
console.log('message!', msg);
messages.push(msg);
}
socket.on('connect', do_on_connect);
socket.on('message', do_on_message_from_server);
function send (msg) {
console.log('Sending message:', msg);
socket.emit('message', msg);
};
</script>
</body>
</html>
{
"name": "chat-example",
"version": "0.0.0",
"description": "A chat example to showcase how to use `socket.io` with a static `express` server",
"main": "server.js",
"repository": "",
"author": "Pahaz Blinov <pahaz.blinov@gmail.com>",
"dependencies": {
"express": "~3.2.4",
"socket.io": "~0.9.14"
}
}
var http = require('http');
var path = require('path');
// WS SERVER
var socketio = require('socket.io');
// HTTP SERVER
var express = require('express');
var router = express(); // создаем роутер
var server = http.createServer(router); // создаем HTTP сервер
var io = socketio.listen(server); // для обмена сообщениями с сервером
router.use(express.static(path.resolve(__dirname, '.'))); // будем отдавать файлы
var messages = [];
var clients = [];
var index = 0;
io.on('connection', function (client) {
for (var i = 0; i < messages.length; i++) {
client.emit('message', messages[i]);
}
clients.push(client);
client.on('disconnect', function () {
clients.splice(clients.indexOf(client), 1);
});
client.on('message', function (data) {
if (!data)
return;
broadcast(data); // рассылаем всем клиентам
messages.push(data);
});
});
function broadcast(data) {
for (var i = 0; i < clients.length; i++) {
var client = clients[i];
client.emit('message', data);
}
}
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
@pahaz

This comment has been minimized.

Copy link
Owner Author

commented Dec 26, 2015

  • npm install для установки пакетов
  • node server.js для запуска
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.