Skip to content

Instantly share code, notes, and snippets.

@ramsunvtech
Created November 29, 2015 02:17
Show Gist options
  • Save ramsunvtech/1e406d85754ccabb4bc5 to your computer and use it in GitHub Desktop.
Save ramsunvtech/1e406d85754ccabb4bc5 to your computer and use it in GitHub Desktop.
Chat with Web Socket
<html>
<head>
<title>Social Message Board</title>
<link rel="stylesheet" type="text/css" href="css\style.css">
</head>
<body>
<div id="message-board">
<div id="messages"></div>
<form id="post-form">
<input type="text" id="message" />
<input type="submit" id="send" value="Send">
</form>
</div>
</body>
<script type="text/javascript" src="js/jquery-min.js"></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="js/message.js"></script>
</html>
(function($) {
var socket = io('http://localhost:4000');
$('#post-form').on('submit', function(e) {
var $message = $('#message');
e.preventDefault();
socket.emit('sendMessage', $message.val());
$message.val('');
});
socket.on('newMessage', function (data) {
$('#messages').append(data + '<br>');
});
})(jQuery);
/**
* Server side Code
**/
var express = require('express'),
app = express(),
path = require('path'),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(path.join(__dirname, '/')));
server.listen('4000');
console.log('server listening to 4000');
io.sockets.on('connection', function (socket) {
socket.on('sendMessage', function (data) {
io.sockets.emit('newMessage', data);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment