JAVA网络编程

一、IP,端口,资源对应的Java类

1.IP

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		InetAddress i = InetAddress.getLocalHost();
		System.out.println(i.getHostName());
		System.out.println(i.getHostAddress());
		System.out.println(i.getByName("www.baidu.com"));
	}

结果为
WIN-3I1CNQDGJ03
172.22.198.33(不要干坏事,写个博客不容易)
www.baidu.com/111.13.100.92
IP对应的Java类为InetAddress,它没有构造方法,通过静态方法获得它的实例。
getHostName():获取主机名
getHostAddress():获取主机的IP地址
getByName():里面传入参数为网址的字符串,返回改网址的IP

2.端口

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		InetSocketAddress isa = new InetSocketAddress("localhost",8888);
		System.out.println(isa.getPort());
		System.out.println(isa.getAddress());
		System.out.println(isa.getHostName());
	}

接口为
8888
localhost/127.0.0.1
localhost
getPort():获取端口号
getAddress():获得IP地址
getHostName():获得主机名

3.资源

资源统称为URI(Universal Resource Identifier),URI分为URL(Universal Resource Locator)和URN(Universal Resource Name),这里我们用URL做演示。
我们输入的网址由:协议+主机名+端口+参数+锚点组成,有的可以省略。

	public static void main(String[] args) throws Exception {
		// TODO Auto-generated method stub
		URL url = new URL("http://www.baidu.com/?userName=p&password=j");
		System.out.println(url.getProtocol());
		System.out.println(url.getFile());
		System.out.println(url.getPath());
		System.out.println(url.getQuery());
	}

结果为
http
/?userName=p&password=j
/
userName=p&password=j

3.1通过URL获取网页信息

	public static void main(String[] args) throws Exception {
		URL url = new URL("https://www.jd.com");
		InputStream is = url.openStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] b = new byte[1024];
		while (bis.read(b) != -1) {
			System.out.println(new String(b));
		}
		bis.close();
		is.close();
	}

结果为www.jd.com首页的源码,太多了,就不展示了

3.2通过URL获取屏蔽爬虫的网页信息

www.jd.com能够放过上面的方式访问,有的网址不行比如www.dianping.com,它不给你访问的权限,但是可以骗他我们是浏览器,从而获取内容。

		URL url = new URL("https://www.dianping.com");
		HttpURLConnection hc = (HttpURLConnection) url.openConnection();
		hc.setRequestMethod("GET");
		hc.setRequestProperty("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36");
		BufferedReader bf = new BufferedReader(new InputStreamReader(hc.getInputStream()));
		String str = null;
		while ((str = bf.readLine()) != null) {
			System.out.println(str);
		}
	}

结果为www.dianping.com首页的源码,太多了,就不展示了。
以上有一些关于IO流的操作,这部分知识不懂得,可以看我的另外一篇博客,写的是关于IO流的IO流操作

二、UDP编程

1.什么是UDP

udp是传输层的协议,它是面向无连接的。

2.UDP发送字符

服务端代码

	public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(8888);
		byte[] buf = new byte[1024 * 60];
		DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
		ds.receive(dp);
		ds.close();
	}

客户端代码

	public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(9999);
		String str = "UDP编程";
		DatagramPacket dp = new DatagramPacket(str.getBytes(), str.getBytes().length,
				new InetSocketAddress("localhost", 8888));
		ds.send(dp);
		ds.close();
	}

注意:UDP是不分主次的,这里的服务端和客户端只是为了方便描述。

3.UDP发送基本数据类型

服务端代码

	public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(8888);
		System.out.println("这是服务端");
		byte[] buf = new byte[1024 * 60];
		DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
		ds.receive(dp);
		ByteArrayInputStream bis = new ByteArrayInputStream(dp.getData(), 0, dp.getData().length);
		DataInputStream dis = new DataInputStream(new BufferedInputStream(bis));
		System.out.println(dis.readUTF());
		System.out.println(dis.readInt());
		System.out.println(dis.readDouble());
		System.out.println(dis.readFloat());
		System.out.println(dis.readChar());
		System.out.println(dis.readBoolean());
		ds.close();
	}

客户端代码

public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(9999);
		System.out.println("这是客户端");
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(bos));
		dos.writeUTF("UDP字符串");
		dos.writeInt(2);
		dos.writeDouble(2.13);
		dos.writeFloat(3.14f);
		dos.writeChar('男');
		dos.writeBoolean(true);
		dos.flush();
		byte[] datas = bos.toByteArray();
		DatagramPacket dp = new DatagramPacket(datas, 0, datas.length, new InetSocketAddress("localhost", 8888));
		ds.send(dp);
		ds.close();
	}

4.UDP发送文件

服务端

	public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(8888);
		System.out.println("这是服务端");
		byte[] buf = new byte[1024 * 60];
		DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
		ds.receive(dp);
		FileOutputStream fos = new FileOutputStream("src/copy.png");
		BufferedOutputStream bos = new BufferedOutputStream(fos);
		bos.write(buf, 0, buf.length);
		ds.close();
	}

客户端

	public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(9999);
		System.out.println("这是客户端");
		byte[] buf = new byte[1024*60];
		FileInputStream fis = new FileInputStream("src/a.png");
		BufferedInputStream bis = new BufferedInputStream(fis);
		bis.read(buf);
		DatagramPacket dp = new DatagramPacket(buf, 0, buf.length, new InetSocketAddress("localhost", 8888));
		ds.send(dp);
		ds.close();
	}

注意UDP一次传输最多60kb。

5.UDP发送JAVA对象

传递对象的类

public class Persion implements Serializable {
	private String name = "张三";
	private int age = 18;

	@Override
	public String toString() {
		return "Persion [name=" + name + ", age=" + age + "]";
	}

}

服务端

	public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(8888);
		System.out.println("这是服务端");
		byte[] buf = new byte[1024 * 60];
		DatagramPacket dp = new DatagramPacket(buf, 0, buf.length);
		ds.receive(dp);
		ByteArrayInputStream bais = new ByteArrayInputStream(dp.getData());
		ObjectInputStream ois = new ObjectInputStream(bais);
		Persion p = (Persion) ois.readObject();
		System.out.println(p);
		ois.close();
		bais.close();
		ds.close();
	}

客户端

	public static void main(String[] args) throws Exception {
		DatagramSocket ds = new DatagramSocket(9999);
		System.out.println("这是客户端");
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		ObjectOutputStream oos = new ObjectOutputStream(baos);
		oos.writeObject(new Persion());
		byte[] buf = baos.toByteArray();
		DatagramPacket dp = new DatagramPacket(buf, 0, buf.length, new InetSocketAddress("localhost", 8888));
		ds.send(dp);
		oos.close();
		baos.close();
		ds.close();
	}

三、TCP编程

1.什么是TCP

它是传输层协议,是面向连接的,效率比UDP低。

2.TCP发送字符串

服务端

	public static void main(String[] args) throws Exception {
		ServerSocket ss = new ServerSocket(8888);
		Socket client = ss.accept();
		InputStream is = client.getInputStream();
		BufferedInputStream bis = new BufferedInputStream(is);
		byte[] b = new byte[1024];
		while (bis.read(b) != -1) {
			System.out.println(new String(b));
		}
		bis.close();
		is.close();
		ss.close();
	}

客户端

	public static void main(String[] args) throws Exception {
		Socket s = new Socket("localhost", 8888);
		OutputStream os = s.getOutputStream();
		BufferedOutputStream bos = new BufferedOutputStream(os);
		bos.write("这是TCP连接".getBytes());
		bos.close();
		os.close();
		s.close();
	}

这里用传输字符串来演示TCP编程的流程,类似的传对象,传文件,传基本数据类型和UDP相差不大,所有就不再TCP里演示。
注意:TCP传输的文件大小没有限制。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值