Java之IO学习(三)网络操作

Java中的网络支持:

  • InetAddress:用于表示网络上的硬件资源,即 IP 地址;
  • URL:统一资源定位符;
  • Sockets:使用 TCP 协议实现网络通信;
  • Datagram:使用 UDP 协议实现网络通信。

 

1、InetAddress:

(1)没有构造函数,只能通过静态方法来创建实例

InetAddress.getByName(String host);
InetAddress.getByAddress(byte[] address);

(2)可以通过调用getAllByName方法来获得所有主机:

InetAddress[] addresses = InetAddress.getAllByName(host);

(3)获取本地主机地址:

InetAddress address = InetAddress.getLocalHost();

(4)例子:如果不在命令行中设置任何参数,那么它将打印出本地主机的因特网地址。

package 网络操作;

import java.net.Inet4Address;
import java.net.InetAddress;

public class InetAddressTest {
	public static void main(String[] args) {
		try {
			if (args.length > 0) {
				String host = args[0];
				InetAddress[] addresses = Inet4Address.getAllByName(host);
				for (InetAddress a : addresses) {
					System.out.println(a);
				}
			} else {
				InetAddress localHostAddress = InetAddress.getLocalHost();
				System.out.println(localHostAddress);
			}
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
	}

}

 

2、URL

可以直接从URL中读取字节流:

public static void main(String[] args) throws IOException {

    URL url = new URL("http://www.baidu.com");

    /* 字节流 */
    InputStream is = url.openStream();

    /* 字符流 */
    InputStreamReader isr = new InputStreamReader(is, "utf-8");

    /* 提供缓存功能 */
    BufferedReader br = new BufferedReader(isr);

    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }

    br.close();
}

 

3、Sockets

  • ServerSocket:服务器端类
  • Socket:客户端类
  • 服务器和客户端通过 InputStream 和 OutputStream 进行输入输出。

    

(1)socket半关闭:套接字连接的一端可以终止其输出,同时仍旧可以接收来自另一端的数据

方法如下:

Socket socket = new Socket(host, port);
Scanner inScanner = new PrintWriter(socket.getOutputStream());
Writer.print(....);
Writer.flush();
socket.shutdownOutput();
while(in.hasNextLine() != null) {String line = inScanner.nextLine(); ... }
socket.close();

 

4、Datagram

  • DatagramSocket:通信类
  • DatagramPacket:数据包类

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值