网络编程

TCP/IP参考模型

应用层   http  ftp 协议

传输层   TCP UDP协议

网际层   IP协议


Tcp transmission control protocol:传输控制协议,传输前采用三次握手建立连接,是可靠的传输协议

Udp user datagram protocol: 数据报协议,不可靠协议,即发出去的协议不一定收的到,无连接:即不管对方在不在,每个包64k ,大文件会拆分。例如qq。

public class NetDemo {
	public static void main(String[] args) throws Exception {
		InetAddress locAdd = InetAddress.getLocalHost();
		System.out.println(locAdd.getHostAddress());// 本地IP地址
		System.out.println(locAdd.getHostName());
		System.out.println(locAdd.isReachable(5000));
		InetAddress remAdd = InetAddress.getByName("www.baidu.com"); // 获得远程InetAddress
		System.out.println(remAdd.getHostAddress());
		System.out.println(remAdd.getHostName());
	}
}

URL读取页面html代码

public class NetDemo {
	public static void main(String[] args) throws Exception {
		URL url = new URL("http", "localhost", 8080,"/index.html");
		URLConnection conn = url.openConnection();
		System.out.println(conn.getContentLength());  // 7662
		System.out.println(conn.getContentType());    // text/html 
		InputStream input = url.openStream();
		Scanner scan = new Scanner(input);
		scan.useDelimiter("\n");
		while(scan.hasNext()){
			System.out.println(scan.next());
		}
	}
}

URLEncoder 编码

URLDecoder解码

public class NetDemo {
	public static void main(String[] args) throws Exception {
		String oldStr = "csdn 程序员";
		String encode = URLEncoder.encode(oldStr,"UTF-8");
		System.out.println("编码后的内容:"+encode);
		String decode = URLDecoder.decode(encode, "UTF-8");
		System.out.println("解码后的内容:"+decode);
	}
}

结果:

编码后的内容:csdn+%E7%A8%8B%E5%BA%8F%E5%91%98
解码后的内容:csdn 程序员
Tcp

服务器端使用ServerSocket  ,accept()方法等待客户端连接,此方法执行后服务器端进入阻塞状态,知道客户端连接后才继续执行
客户端使用Socket  ,getInputstream() 获得服务器端的输出信息,服务器端通过 getOutputStream() 获得客户端输出信息

public class NetDemo {
	public static void main(String[] args) throws Exception {
		ServerSocket server = new ServerSocket(8888);
		System.out.println("服务器在8888端口等待客户端访问");
		Socket client = server.accept();
		String str = "hello world";
		PrintStream out = new PrintStream(client.getOutputStream());
		out.println(str);
		out.close();
		client.close();
		server.close();
	}
}

运行结果:服务器在8888端口等待客户端访问

服务器程序一执行到accept()方法后,程序进入了阻塞状态,直到客户端连接后改变

可以使用telnet open localhost 8888  取得服务器的输出信息
服务器端此时只处理一个请求,所以也将关闭

public class NetDemo {
	public static void main(String[] args) throws Exception {
		Socket client = new Socket("localhost", 8888);
		BufferedReader buf = new BufferedReader(new InputStreamReader(client.getInputStream()));
		String str = buf.readLine();
		System.out.println("服务器端输出的内容:"+str);
		buf.close();
	}
}
结果:服务器端输出的内容:hello world
使用循环和多线程方式回应程序


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值