Java語言支持UDP和TCP兩種網絡通信協議,本文將介紹一些Java中的UDP和TCP案例:
以下是一個基于UDP協議的案例,用于發送和接收數據包:
DatagramSocket socket = new DatagramSocket(); String message = "Hello UDP"; byte[] buf = message.getBytes(); InetAddress addr = InetAddress.getByName("127.0.0.1"); DatagramPacket packet = new DatagramPacket(buf, buf.length, addr, 8888); socket.send(packet); byte[] receiveBuf = new byte[1024]; packet = new DatagramPacket(receiveBuf , receiveBuf.length); socket.receive(packet); String receiveMessage = new String(packet.getData(),0,packet.getLength()); System.out.println("Received message:" + receiveMessage); socket.close();
以下是基于TCP協議的案例,用于建立服務端和客戶端之間的連接:
// 服務端 ServerSocket serverSocket = new ServerSocket(8888); Socket socket = serverSocket.accept(); DataInputStream dis = new DataInputStream(socket.getInputStream()); String message = dis.readUTF(); System.out.println("Received message:" + message); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF("Hello TCP"); dos.flush(); dis.close(); dos.close(); socket.close(); serverSocket.close(); // 客戶端 Socket socket = new Socket("127.0.0.1", 8888); DataInputStream dis = new DataInputStream(socket.getInputStream()); DataOutputStream dos = new DataOutputStream(socket.getOutputStream()); dos.writeUTF("TCP server, I'm the client"); dos.flush(); String message = dis.readUTF(); System.out.println("Received message:" + message); dis.close(); dos.close(); socket.close();
以上是一些基于UDP和TCP協議的案例,Java語言具有強大的網絡通信功能,可以方便地實現各種網絡應用程序。
上一篇css 單選框 選擇
下一篇css 卡片式背景