网络编程示例

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!\r\n');

});

 

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!\r\n');

      });

     

});

 

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();

转载于:https://www.cnblogs.com/SLchuck/p/4893041.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个使用 Java NIO(New I/O)进行网络编程的简单示例: ```java import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class NIOExample { public static void main(String[] args) throws IOException { // 创建一个线程池用于处理客户端连接 ExecutorService executor = Executors.newFixedThreadPool(10); // 创建 ServerSocketChannel 并绑定端口 ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); serverSocketChannel.bind(new InetSocketAddress("localhost", 8080)); System.out.println("Server started on port 8080"); while (true) { // 接受客户端连接 SocketChannel socketChannel = serverSocketChannel.accept(); // 使用线程池处理客户端连接 executor.execute(() -> handleClient(socketChannel)); } } private static void handleClient(SocketChannel socketChannel) { try { ByteBuffer buffer = ByteBuffer.allocate(1024); // 读取客户端发送的数据 int bytesRead = socketChannel.read(buffer); while (bytesRead != -1) { buffer.flip(); while (buffer.hasRemaining()) { System.out.print((char) buffer.get()); } buffer.clear(); bytesRead = socketChannel.read(buffer); } // 响应客户端 String response = "Hello from server"; ByteBuffer responseBuffer = ByteBuffer.wrap(response.getBytes()); socketChannel.write(responseBuffer); // 关闭连接 socketChannel.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 这个示例创建了一个简单的服务器,监听本地的 8080 端口。当客户端连接时,会使用线程池处理连接,并读取客户端发送的数据。然后,服务器会向客户端发送 "Hello from server" 的响应,并关闭连接。 请注意,这只是一个简单的示例,实际的网络编程可能涉及更复杂的逻辑和处理。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值