1. 程式人生 > >Java 使用udp協議傳送資料

Java 使用udp協議傳送資料

最近工作中用到使用udp和服務端通訊,所以記錄下….

//客戶端
public static void send(byte[] data,String ip,int port) throws Exception{
        DatagramSocket s = new DatagramSocket(null);
        s.setReuseAddress(true);
        //這裡是指定傳送的客戶端埠,因為該協議規定只接收由此埠發出的資料
        s.bind(new InetSocketAddress(9001));

        DatagramPacket p = new
DatagramPacket(data,0,data.length, new InetSocketAddress(ip, port)); s.send(p); }
//服務端
public class SocketUdp {
    final private static String TAG = "SocketUdp: ";

    public static void main(String args[]) {
        DatagramSocket socket = null;
        DatagramPacket datapacket = null
; InetSocketAddress address = null; try { address = new InetSocketAddress(InetAddress.getLocalHost(), 9090); socket = new DatagramSocket(address); // socket.bind(address); byte buf[] = new byte[1024]; datapacket = new DatagramPacket(buf, buf.length); System.out
.println("等待接收客戶端資料..."); socket.receive(datapacket); buf = datapacket.getData(); InetAddress addr = datapacket.getAddress(); int port = datapacket.getPort(); System.out.println("客戶端傳送的資料: " + new String(buf) ); System.out.println("資料來源 " + addr + ":" + port); SocketAddress toAddress = datapacket.getSocketAddress(); String sendStr = "server return ok"; buf = sendStr.getBytes(); datapacket = new DatagramPacket(buf, buf.length); datapacket.setSocketAddress(toAddress); socket.send(datapacket); System.out.println("傳送結束"); } catch (UnknownHostException e) { System.out.println(TAG + e.getMessage()); e.printStackTrace(); } catch (SocketException e) { System.out.println(TAG + e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println(TAG + e.getMessage()); e.printStackTrace(); } } }