Skip to content

Instantly share code, notes, and snippets.

@whaleinvasion
Forked from orkaplan/chat.html
Created August 3, 2017 23:31
Show Gist options
  • Save whaleinvasion/24e397d298b18d8b421e84d4c72642c0 to your computer and use it in GitHub Desktop.
Save whaleinvasion/24e397d298b18d8b421e84d4c72642c0 to your computer and use it in GitHub Desktop.
simple node.js socket.io client/server example
<html>
<head>
<title>Node.js IL Chat</title>
<script type="text/javascript" src="/jquery-1.6.4.min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script language="javascript">
var socket;
$(document).ready(function()
{
socket = io.connect('/');
socket.on('message', function (data) {
var content = $('#messages').html() + data + '<br/>';
$('#messages').html(content);
});
$('#message').bind('keypress', function(e) {
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) { //Enter keycode
postMessage();
}
});
});
function postMessage()
{
if (socket) {
socket.emit('message', $('#message').val());
$('#message').val('');
}
}
</script>
<style>
body {
background-color:#000000;
color: green;
}
</style>
</head>
<body>
<h2 class="white">Post your messages</h3>
<table>
<tr><td class="white">Your Message:</td><td><input id="message" type="text" size="50"></td></tr>
</table>
<h2 class="white">Messages</h3>
<div id="messages">
</div>
</body>
</html>
var Express = require('express'),
app = Express.createServer(),
io = require('socket.io').listen(app);
io.configure('production', function(){
io.enable('browser client etag');
io.set('log level', 1);
io.set('transports', [
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling',
]);
});
io.configure('development', function(){
io.set('transports', ['websocket']);
});
app.get('/', function (req, res) {
res.redirect('/chat.html');
});
app.use(Express.static(__dirname + '/static'));
app.listen(process.env.PORT || process.argv[3] || 8080);
io.sockets.on('connection', function(client){
var userName;
console.log("user connected!");
client.emit('message', 'please insert user name');
client.on('message', function(message){
if (!userName) {
userName = message;
console.log(userName + ' is connected :)');
client.emit('message', 'Welcome ' + userName);
client.broadcast.emit('message', userName + ' is connected');
}
else {
client.emit('message', 'me: ' + message);
client.broadcast.emit('message', userName + ' says: ' + message);
}
});
client.on('disconnect', function() {
if (userName) {
console.log(userName + " left");
client.broadcast.emit('message', userName + ' left us :(');
}
else {
console.log("anonymous left");
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment