Java核心代码例程之:DatagramClientDemo.java

发表于:2007-06-22来源:作者:点击数: 标签:
import java .io.*; importjava .net .*; /** *DemonstrateshowtoDatagramclient * *@seeDatagramServerDemo ***/ publicclassDatagramClientDemo { publicstaticvoidmain(Stringargs[])throwsException { byteData[]=newbyte[20]; StringsendMsg=Hello; sen

   
import java.io.*;
import java.net.*;


/**
 * Demonstrates how to Datagram client
 *
 * @see DatagramServerDemo
 ***/

public class DatagramClientDemo
{
    public static void main(String args[]) throws Exception
    {
        byte Data[] = new byte[20];
        String sendMsg="Hello";
        sendMsg.getBytes(0, sendMsg.length(), Data, 0);

        // Client on port 4444, Server on 5555
        DatagramSocket socket = new DatagramSocket(4444);
        DatagramPacket packet = new DatagramPacket(Data, 6,
                                    InetAddress.getByName("localhost"),
                                    5555);
        socket.send(packet);

        packet = new DatagramPacket(Data, 20);
        socket.receive(packet);
        String received = new String(packet.getData(), 0);
        System.out.println(received);
    }
}

原文转自:http://www.ltesting.net