Created
November 15, 2013 11:26
-
-
Save davidtucker/7482905 to your computer and use it in GitHub Desktop.
Sample Websockets Chat Server with Socket.IO
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
// Include Both Express and Socket.io | |
var express = require('express'); | |
var socketIO = require('socket.io'); | |
// Include the core modules for http and path | |
var path = require('path'); | |
var http = require('http'); | |
// Setup Express to serve static files from static directory | |
var app = express(); | |
app.configure(function(){ | |
app.use(express.static(path.join(__dirname, 'static'))); | |
}); | |
// Set server to listen on defined port | |
var server = http.createServer(app).listen(8089); | |
// Setup Socket.IO | |
var io = socketIO.listen(server); | |
io.sockets.on('connection', function (socket) { | |
socket.on('message', function (data) { | |
io.sockets.emit('message', data); | |
}); | |
}); |
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
<html> | |
<head> | |
<title>Chat Example</title> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> | |
<script src="/socket.io/socket.io.js"></script> | |
<script> | |
var socket = io.connect('http://localhost:8089/'); | |
socket.on('message', function(data) { | |
console.log("Receiving Message"); | |
$('#chat').append(data.message + '\n'); | |
}); | |
$(function() { | |
$('#sendMessage').click(function() { | |
var username = $('#username').val(); | |
var message = $('#message').val(); | |
socket.emit('message', { message: username + ": " + message }); | |
$('#message').val(''); | |
}); | |
}); | |
</script> | |
</head> | |
<body> | |
<textarea id="chat" style="width: 600px;height: 600px;"></textarea> | |
<div> | |
Username: <input type="text" id="username" /> | |
Message: <input type="text" id="message" /> | |
</div> | |
<div> | |
<input type="button" id="sendMessage" value="Send Message" /> | |
</div> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment