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

发表于:2007-06-22来源:作者:点击数: 标签:
import java .io.*; importjava .net .*; /** *DemonstrateshowtowriteDatagramserver * *@seeDatagramClientDemo ***/ publicclassDatagramServerDemo { publicstaticvoidmain(Stringargs[])throwsException { byteData[]=newbyte[20]; //Clientonport4444,

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


/**
 * Demonstrates how to write Datagram server
 *
 * @see DatagramClientDemo
 ***/

public class DatagramServerDemo
{
    public static void main(String args[]) throws Exception
    {
        byte Data[] = new byte[20];

        // Client on port 4444, Server on 5555
        DatagramSocket socket = new DatagramSocket(5555);
        DatagramPacket packet = new DatagramPacket(Data, 20);

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

        String sendMsg="Hello Back";
        sendMsg.getBytes(0, sendMsg.length(), Data, 0);
        packet  = new DatagramPacket(Data, 20,
                                packet.getAddress(),
                                packet.getPort());
        socket.send(packet);
    }
}

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