zoukankan      html  css  js  c++  java
  • node.js版简单客户端和服务端通讯源码

    一、服务器端:

     1 var app = require('http').createServer(handler),
    2 io = require('socket.io').listen(app),
    3 fs = require('fs');
    4
    5 app.listen(999);
    6
    7 function handler(req, res) {
    8 fs.readFile(__dirname+'/client.htm',
    9 function(err, data){
    10 res.writeHead(200);
    11 res.end(data);
    12 });
    13 }
    14
    15 io.sockets.on('connection',function(socket){
    16
    17 socket.on('msg',function(data){
    18 console.log('Get a msg from client');
    19 console.log(data);
    20 socket.broadcast.emit('usermsg',data);
    21 });
    22 });

    二、客户端代码:

    <html>
    <head>
    <title>Chat Room</title>
    <script src="http://10.190.19.38:999/socket.io/socket.io.js"></script>
    <script type="text/javascript">
    var hotline = io.connect('http://10.190.19.38:999');
    hotline.emit(
    'msg','hi it is client!');

    hotline.on(
    'user message',function(data){
    document.getElementById(
    'chatbox').innerHTML += data+"<br>";
    });

    function sendToSer(){
    text
    = document.getElementById('send-content').value;
    hotline.emit(
    'msg',text);
    }
    </script>
    </head>
    <body>
    <h1>Chat Room</h1>
    <input type='text' id= 'send-content'>
    <input type='button' value='send' onclick='sendToSer()'>
    <div id="chatbox"></div>
    </body>
    </html>

    参考连接:http://www.cnblogs.com/hsxixi/archive/2011/12/25/2300883.html

    注释待加。。。。。。。。。。。。。。。

  • 相关阅读:
    MYSQL判断某个表是否已经存在
    百度、雅虎、谷歌搜索引擎接口调用注意事项
    Codeigniter整合Tank Auth权限类库的教程
    短链接的生成算法
    自定义String
    运算符和结合性
    字符串类封装
    运算符重载
    数组类封装
    友元
  • 原文地址:https://www.cnblogs.com/itshark/p/2344270.html
Copyright © 2011-2022 走看看