集册 Java实例教程 创建DatagramSocket客户端

创建DatagramSocket客户端

欢马劈雪     最近更新时间:2020-01-02 10:19:05

374
创建DatagramSocket客户端

import java.io.*;/*时 代 J a v a 公 众 号 提供*/

import java.net.*;

import java.util.*;


public class QuoteClient {

    public static void main(String[] args) throws IOException {


        if (args.length != 1) {

            System.out.println("Usage: java QuoteClient <hostname>");

            return;

        }


        // get a datagram socket

        DatagramSocket socket = new DatagramSocket();


        // send request

        byte[] buf = new byte[256];//时代Java - nowjava.com 提供

        InetAddress address = InetAddress.getByName(args[0]);

        DatagramPacket packet = new DatagramPacket(buf, buf.length,

                address, 4445);

        socket.send(packet);


        // get response

        packet = new DatagramPacket(buf, buf.length);

        socket.receive(packet);


        // display response

        String received = new String(packet.getData(), 0,

                packet.getLength());

        System.out.println("Quote of the Moment: " + received);


        socket.close();

    }

}


展开阅读全文