原创

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();
        }
    }

}
正文到此结束
本文目录