java使用InetAddress类表示一个IP地址:
构造器:
常用方法:
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
Socket类的常用构造器:
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的基本结构由5部分组成:<传输协议>://<主机名>:<端口号>/<文件名>#片段名?参数列表
URL对象构造器:
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 }
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(); }