🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## Java专题十二:网络 [TOC] ### 12.1.套接字 - `Socket`: 客户端套接字 - `ServerSocket`: 服务器端套接字 > Linux中Socket编程:[http://www.man7.org/linux/man-pages/man2/socket.2.html](http://www.man7.org/linux/man-pages/man2/socket.2.html) <table > <tr> <th style="width:70%">SOCKET_API</th> <th style="width:30%">DESCRIPTION</th> </tr> <tr> <td>int socket(int domain, int type, int protocol);</td> <td>create an endpoint for communication</td> </tr> <tr> <td>int accept(int sockfd, struct sockaddr *addr, socklen_t *addrlen); </td> <td>accept a connection on a socket</td> </tr> <tr> <td> int connect(int sockfd, const struct sockaddr *addr, socklen_t addrlen);</td> <td>initiate a connection on a socket</td> </tr> <tr> <td> int bind(int sockfd, const struct sockaddr *add, socklen_t addrlen);</td> <td>bind a name to a socket </td> </tr> <tr> <td>int listen(int sockfd, int backlog);</td> <td> listen for connections on a socket </td> </tr> <tr> <td>ssize_t send(int sockfd, const void *buf, size_t len, int flags); </td> <td>send a message on a socket </td> </tr> <tr> <td>ssize_t sendto(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen); </td> <td>send a message on a socket </td> </tr> <tr> <td>ssize_t recv(int sockfd, const void *buf, size_t len, int flags);</td> <td>receive a message on a socket</td> </tr> <tr> <td>ssize_t recvfrom(int sockfd, const void *buf, size_t len, int flags, const struct sockaddr *dest_addr, socklen_t addrlen);</td> <td>receive a message on a socket</td> </tr> <tr> <td>ssize_t read(int fd, void *buf, size_t count); </td> <td>read from a file descriptor</td> </tr> <tr> <td>ssize_t write(int fd, const void *buf, size_t count); </td> <td>write to a file descriptor</td> </tr> <tr> <td>int close(int fd); </td> <td>close a file descriptor</td> </tr> </table> #### 12.1.1 服务器端(`java.net.ServerSocket`) * 创建Socket(`new ServerSocket()`) * 绑定端口(`bind(SocketAddress endpoint)`) * 监听端口(`accept()`) * 等待客户端连接 * 接收和发送数据(`getInputStream()、getOutputStream()`) * 关闭Socket(`close()`) #### 12.1.2客户端(`java.net.Socket`) * 创建Socket(`Socket()`) * 发起连接(`connect(SocketAddress endpoint)`) * 发送和接收数据(`getOutputStream()、getInputStream()`) * 关闭Socket(`close()`) ![](https://img.kancloud.cn/4d/29/4d2919823ccbd00a9de874a3cf0e7044_280x354.png) ### 12.2.高级API java.net 包中的许多类可以提供更加高级的抽象,允许方便地访问网络上的资源。 - `URI`: 表示统一资源标识符(URI)引用 - `URL`: 表示统一资源定位器,即指向万维网上“资源”的指针 - `URLConnection`: 表示应用程序和URL之间的通信链接 - `HttpURLConnection`: 支持HTTP特定功能的URLConnection,规范见[http://www.w3.org/pub/www/Protocols/](http://www.w3.org/pub/www/Protocols) 例:从网络上下载文件并保存到本地,详细参考[NetTools](https://github.com/15045120/git-docs/blob/master/tools/NetTools.java) ``` NetTools.download("https://dl.google.com/android/repository/platform-tools-latest-windows.zip",""); ``` ``` public static boolean download(String url, String saveDir) throws URISyntaxException, IOException { // get download file name String fileName = url.substring(url.indexOf('/')); if (saveDir == null || saveDir.trim().equals("")){ saveDir = ""; }else{ File out = new File(saveDir); if (!out.exists() || !out.isDirectory()){ throw new FileNotFoundException(); } } // open connection URI uri = new URI(url); URL url0 = uri.toURL(); HttpURLConnection conn = (HttpURLConnection)url0.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36"); conn.connect(); // response is ok if (conn.getResponseCode() == HttpURLConnection.HTTP_OK){ InputStream is = conn.getInputStream(); File file = new File(saveDir, fileName); FileOutputStream fos = new FileOutputStream(new File("platform-tools-latest-windows.zip")); byte[] buf = new byte[1024]; int readCount; while((readCount = is.read(buf)) > 0){ fos.write(buf, 0, readCount); } is.close(); fos.close(); return true; } return false; } ```