lirongfei123
5/1/2017 - 8:32 AM

simple node.js socket.io client/server example

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");
		}
    });
});