Java 网络编程
java在java.net包提供了丰富的api供网络编程,主要包括了:
URLConnection, HttpURLConnection用于从服务器端获取数据;
ServerSocket和Scoket建立TCP服务器和客户端;
DatagramSocket建立UDP服务器和客户端;
- ServerSocket和Scoket建立TCP/IP连接
首先,我们需要通过ServerSocket建立监听客户端TCP连接请求。当监听到客户端的请求后,Server会分配一个Socket与客户端通信。
创建客户端用于发送和接收数据变得相当简单:
Socket socket = new Socket("localhost", 8080); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); out.println("test"); BufferedReader in = new BufferedReader(new InputStreamReader( socket.getInputStream())); System.out.println(in.readLine()); // 必须输出换行,否则不会输出任何数据给客户 socket.close();
服务器端也相当简单:
ServerSocket serverSocket = new ServerSocket(8080); Socket clientSocket = serverSocket.accept(); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader( clientSocket.getInputStream())); String line; while ((line = in.readLine()) != null) { out.println("From Server: " + line); // 必须输出换行,否则不会输出任何数据给客户 } clientSocket.close(); serverSocket.close();
- DatagramSocket建立UDP连接
与TCP连接不同,UDP并没有严格意义上的服务器端和客户端之分。双方都可以发送数据给对方,接收方不一定接收到数据,发送方也不知道数据是否被接收。发送的数据也不一定按原来的顺序接收。很显然,由于不需要彼此事先建立连接,故而省去了很多不必要的开销。这对于不关心少量数据丢失的应用十分有用,如直播。
public class UDPTest { public static void main(String[] args) throws IOException, InterruptedException { new Thread(new Runnable() { @Override public void run() { try { receive(); // must start a new thread } catch (IOException e) { e.printStackTrace(); } } }).start(); send(); } public static void send() throws IOException { DatagramSocket datagramSocket = new DatagramSocket(); byte[] buffer = "test udp".getBytes(); InetAddress receiverAddress = InetAddress.getLocalHost(); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, receiverAddress, 8800); datagramSocket.send(packet); // not block datagramSocket.close(); } public static void receive() throws IOException { DatagramSocket datagramSocket = new DatagramSocket(8800); byte[] buffer = new byte[10]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); datagramSocket.receive(packet); // it will block until data received System.out.println(new String(packet.getData())); datagramSocket.close(); } }
- HttpURLConnection与服务器通信
GET
URL url = new URL("http://163.com"); URLConnection conn = url.openConnection(); try (BufferedReader reader = new BufferedReader(new InputStreamReader( conn.getInputStream()));) { String line = null; while (null != (line = reader.readLine())) { System.out.println(line); } }
POST
conn.setDoOutput(true); // post PrintWriter writer = new PrintWriter(conn.getOutputStream()); //application/x-www-form-urlencoded writer.close();
这里有个JarURLConnection类,用于获取jar包相关的信息:
//jar:<url>!/{entry} String urlString = "jar:http://butterfly.jenkov.com/" + "container/download/" + "jenkov-butterfly-container-2.9.9-beta.jar!/"; URL jarUrl = new URL(urlString); JarURLConnection connection = (JarURLConnection) jarUrl.openConnection(); Manifest manifest = connection.getManifest();