Java基础之网络编程
IP(InetAddress)
java使用InetAddress类表示一个IP地址:
构造器:
- public static InetAddress getLocalHost()
- public static InetAddress getByName(String host) : host支持ip地址和域名
常用方法:
- public String getHostAddress():返回 IP 地址字符串(以文本表现形式)。
- public String getHostName():获取此 IP 地址的主机名
- public boolean isReachable(int timeout):测试是否可以达到该地址
InetAddress ip1 = InetAddress.getByName("8.8.8.8");
System.out.println(ip1); // /8.8.8.8
InetAddress ip2 = InetAddress.getByName("www.baidu.com");
System.out.println(ip2); // www.baidu.com/39.156.66.18
System.out.println(ip2.getHostAddress()); // 39.156.66.18
System.out.println(ip2.getHostName()); // www.baidu.com
InetAddress localHost = InetAddress.getLocalHost();
System.out.println(localHost); // LegionR7000/192.168.174.1
System.out.println(localHost.getHostAddress()); // 192.168.174.1
System.out.println(localHost.getHostName()); // LegionR7000
端口
- 端口标识正在计算机上运行的进程(程序)
- 端口号与IP地址组合得出一个网络套接字:Socket
Socket类
Socket类的常用构造器:
- public Socket(InetAddress address,int port)创建一个流套接字并将其连接到指定 IP 地址的指定端口号。
- public Socket(String host,int port)创建一个流套接字并将其连接到指定主机上的指定端口号。
Socket类的常用方法:
- public InputStream getInputStream()返回此套接字的输入流。可以用于接收网络消息
- public OutputStream getOutputStream()返回此套接字的输出流。可以用于发送网络消息
- public InetAddress getInetAddress()此套接字连接到的远程 IP 地址;如果套接字是未连接的,则返回 null。
- public InetAddress getLocalAddress()获取套接字绑定的本地地址。 即本端的IP地址
- public int getPort()此套接字连接到的远程端口号;如果尚未连接套接字,则返回 0。
- public int getLocalPort()返回此套接字绑定到的本地端口。 如果尚未绑定套接字,则返回 -1。即本端的端口号。
- public void close()关闭此套接字。套接字被关闭后,便不可在以后的网络连接中使用(即无法重新连接或重新绑定)。需要创建新的套接字对象。 关闭此套接字也将会关闭该套接字的 InputStream 和
OutputStream。 - public void shutdownInput()如果在套接字上调用 shutdownInput() 后从套接字输入流读取内容,则流将返回 EOF(文件结束符)。 即不能在从此套接字的输入流中接收任何数据。
- public void shutdownOutput()禁用此套接字的输出流。对于 TCP 套接字,任何以前写入的数据都将被发送,并且后跟 TCP 的正常连接终止序列。 如果在套接字上调用 shutdownOutput() 后写入套接字输出流,则该流将抛出 IOException。 即不能通过此套接字的输出流发送任何数据。
ServerSocket 对象
- ServerSocket 对象负责等待客户端请求建立套接字连接,类似邮局某个窗口中的业务员。也就是说,服务器必须事先建立一个等待客户请求建立套接字连接的ServerSocket对象。
- 所谓“接收”客户的套接字请求,就是accept()方法会返回一个 Socket 对象
public class TcpTest1 {
@Test
public void client() throws IOException {
// 1.创建socket对象,指明服务器的IP和端口
Socket socket = new Socket("127.0.0.1", 5000);
// 2.获取输出流并输出数据
OutputStream out = socket.getOutputStream();
out.write("你好,这里是客户端发来的消息".getBytes());
// 3.关闭资源
out.close();
socket.close();
}
@Test
public void server() throws IOException {
// 1.创建服务端ServerSocket,指定自身端口
ServerSocket serverSocket = new ServerSocket(5000);
// 2.调用accept(),表示接收来自于客户端的socket
Socket socket = serverSocket.accept();
// 3.获取输入流读取数据
InputStream in = socket.getInputStream();
// 不建议写法:有乱码
// byte[] buffer = new byte[5];
// int len;
// while ((len = in.read(buffer)) != -1) {
// String str = new String(buffer, 0, len);
// System.out.print(str);
// }
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[5];
int len;
while ((len = in.read(buffer)) != -1) {
baos.write(buffer, 0, len);
}
System.out.print(baos.toString("UTF-8"));
// 4.关闭资源
in.close();
baos.close();
socket.close();
serverSocket.close();
}
}
URL类
URL的基本结构由5部分组成:<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
URL对象构造器:
- public URL (String spec):通过一个表示URL地址的字符串可以构造一个URL对象。例如:URL url = new URL ("http://www.atguigu.com/");
- public URL(URL context, String spec):通过基 URL 和相对 URL 构造一个 URL 对象。例如:URL downloadUrl = new URL(url, “download.html")
- public URL(String protocol, String host, String file); 例如:new URL("http","www.atguigu.com", “download. html");
- public URL(String protocol, String host, int port, String file); 例如: URL gamelan = newURL("http", "www.atguigu.com", 80, “download.html");
URL对象常用方法:
- public String getProtocol() 获取该URL的协议名
- public String getHost() 获取该URL的主机名
- public String getPort() 获取该URL的端口号
- public String getPath() 获取该URL的文件路径
- public String getFile() 获取该URL的文件名
- public String getQuery() 获取该URL的查询名
public void testUrl() throws MalformedURLException {
URL url = new URL("http://localhost:8080/examples/beauty.jpg?a=1&b=2");
System.out.println(url.getProtocol()); // http
System.out.println(url.getHost()); // localhost
System.out.println(url.getPort()); // 8080
System.out.println(url.getPath()); // /examples/beauty.jpg
System.out.println(url.getFile()); // /examples/beauty.jpg?a=1&b=2
System.out.println(url.getQuery()); // a=1&b=2
}
URLConnection类
public void testUrlConnection() throws Exception {
URL url = new URL("https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.connect();
InputStream in = conn.getInputStream();
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream("baidu.png"));
byte[] buffer = new byte[10];
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
in.close();
out.close();
conn.disconnect();
}