最近在學Java,正好作一些筆記,以防止本身忘了。java
//UdpClient.java import java.io.IOException; import java.io.UnsupportedEncodingException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetSocketAddress; import java.net.SocketException; public class UdpClient { private static DatagramSocket clientSocket = null; private InetSocketAddress serverAddress = null; public UdpClient(String host, int port) throws SocketException { clientSocket = new DatagramSocket( ); //建立socket serverAddress = new InetSocketAddress(host, port); //綁定sever的ip與port } public void send(String msg) throws IOException { try { byte[] data = msg.getBytes("utf-8"); DatagramPacket packet = new DatagramPacket(data, data.length, serverAddress); clientSocket.send(packet); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //main方法用於測試 public static void main(String[] args) throws Exception { UdpClient client = new UdpClient("127.0.0.1", 14586); client.send("hello world"); clientSocket.close(); } }
//UdpServer.java import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.SocketException; public class UdpServer { private byte[] data = new byte[1024]; private static DatagramSocket serverSocket = null; private DatagramPacket packet = null; public UdpServer(int port) throws SocketException { serverSocket = new DatagramSocket(port); System.out.println("sever start!"); } //接收消息 public String recieve() throws IOException { packet = new DatagramPacket(data, data.length); serverSocket.receive(packet); String info = new String(packet.getData(), 0, packet.getLength()); System.out.println("recieve message from " + packet.getAddress().getHostAddress() + ":" + packet.getPort() + "\t"+ info); return info; } //本地測試 public static void main(String[] args) throws Exception { UdpServer server = new UdpServer(14586); server.recieve(); } }
sever start!
recieve message from 127.0.0.1:64478 hello worldsocket