| |
接收网络服务器发送来的数据 /* readnet.java 接收网络服务器发送来的数据,并将其原样输出到屏幕上 使用方法:java readnet dns port 例:java readnet www.domain.cn 80 */
import java.io.*; import java.net.*;
public class readnet { public static void main(string[] args) { byte[] buff = new byte[1024]; socket readsocket = null; // 连接服务器的socket inputstream instr = null; // 读取数据的对象 boolean cont = true;
//对于指定的端口,生成socket //生成instr对象,准备读取数据 try { readsocket = new socket(args[0], integer.parseint(args[1])); instr = readsocket.getinputstream(); } catch (exception e) { system.err.println("文件没有找到"); system.exit(1); }
//数据读取未完时执行以下的循环 while (cont) { try { //读取数据 int n = instr.read(buff); //写入到system.out中 system.out.write(buff, 0, n); } catch (exception e) { cont = false; } } //断开连接 try { instr.close(); } catch (exception e) { //网络关闭失败 system.err.println("网络错误"); system.exit(1); } } }
|
|