版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u014252478/article/details/83574814
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:数据包类