Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // package.json
- {
- "name": "socket-chat-example",
- "version": "0.0.1",
- "description": "my first socket.io app",
- "dependencies": {}
- }
- $ npm install --save express
- $ npm install --save socket.io
- // index.js
- var app = require('express')(); // import class (node_modules)
- var http = require('http').Server(app);
- var io = require('socket.io')(http);
- app.get('/', function(req, res){ // localhost:3000/
- res.sendfile('index.html');
- });
- app.get('/link', function(req, res){ // localhost:3000/link
- res.sendfile('link.html');
- });
- io.on('connection', function(socket){ // connected to client
- socket.on('chat message', function(msg){ // receiving 'message' from client
- io.emit('chat message', msg); // sending 'message' to client
- });
- });
- http.listen(3000, function(){ // port
- console.log('listening on *:3000');
- });
- //index.html
- <!doctype html>
- <html>
- <head>
- <title>Socket.IO chat</title>
- <script src="/socket.io/socket.io.js"></script>
- <script src="http://code.jquery.com/jquery-1.11.1.js"></script>
- </head>
- <body>
- <ul id="messages"></ul>
- <form action="">
- <input id="m" />
- <button>Send</button>
- </form>
- <a href="link"> Link </a>
- <script>
- var socket = io(); // io('127.0.0.1');
- $('form').submit(function(){
- socket.emit('chat message', $('#m').val()); // sending message to server
- $('#m').val('');
- return false; // Stopping the submit
- });
- socket.on('chat message', function(msg){ // receiving message from server
- $('#messages').append($('<li>').text(msg));
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment