zoukankan      html  css  js  c++  java
  • 网络编程示例

    1. 网络编程

    1.1 TCP

    //server

    var net = require('net');

    var server = net.createServer(function(socket){

          socket.on('data',function(data){

                 socket.write('hello world');

          });

         

          socket.on('end',function(){

                 console.log('end');

          });

         

          socket.write('welcome');

    });

    server.listen(8000,'127.0.0.1',function(){

          console.log('server bound');

    });

    //client

    var net = require('net');

    var client = net.connect(8000,'127.0.0.1',function(){

          console.log('client connected');

          client.write('hi! ');

    });

    client.on('data',function(data){

          console.log(data.toString());

          client.end();

    });

    client.on('end',function(){

          console.log('client end');

    });

    1.2 UDP

    //server

    var dgram = require('dgram');

    var server = dgram.createSocket('udp4');

    server.on('message',function(msg,rinfo){

          console.log(msg+rinfo.address+rinfo.port);

    });

    server.on('listening',function(){

          var address = server.address();

          console.log(address.address+address.port);

    });

    server.bind(9000,'127.0.0.1');

    //client

    var dgram = require('dgram');

    var client = dgram.createSocket('udp4');

    var message = new Buffer('hello world');

    client.send(message,0,message.length,9000,'127.0.0.1',function(err,bytes){

          client.close();

    });

    1.3 HTTP

    //server

    var http = require('http');

    var server = http.createServer(function(req,res){

          res.writeHead(200,{'Content-Type':'text/plain'});

          var chunks = [];

          req.on('data',function(chunk){

                 chunks.push(chunk);

          })

          req.on('end',function(){

                 var buffer = Buffer.concat(chunks);

                 res.end('hello world! ');

          });

         

    });

    server.listen(9999,'127.0.0.1');

    //client

    var options = {

          hostname:'127.0.0.1',

          port:9999,

          path:'/',

          method:'GET'

    }

    var req = http.request(options,function(res){

          console.log(res.statusCode);

          console.log(JSON.stringify(res.headers));

          res.setEncoding('utf8');

          res.on('data',function(chunk){

                 console.log(chunk);

          })

    });

    req.end();

  • 相关阅读:
    Android测试:从零开始3—— Instrumented单元测试1
    Android测试:从零开始2——local单元测试
    自定义封装 banner 组件
    常用表单 组件封装
    ContentProvider域名替换小工具
    接口回调封装
    日常记录-代码中Background后Padding 失效
    EditText 限制输入整数和小数 的位数
    (求助)对某一颜色,设置透明度 alpha 后,其他使用该颜色的地方 受到影响!!!!原因未知
    图片选择器ImageEditContainer
  • 原文地址:https://www.cnblogs.com/SLchuck/p/4893041.html
Copyright © 2011-2022 走看看