1

我想测试我的程序,它在发送者接收者DatagramSocket之间发送数据。我应该如何测试在类之间发送数据?

这是我的发件人代码...

public class CheckIn {

    private String patientName;
    private String pTime;
    private int portnumber;

    public CheckIn(String pname, String time, int port){
        patientName = pname;
        pTime = time;
        portnumber = port;
        process();
    }

    public void process() {
        try {
            DatagramSocket is = new DatagramSocket(5800,InetAddress.getLocalHost());
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            String n = "Your "+"\n" + pTime + "\n" + patientName + " has arrived";
            oos.writeObject(n);
            byte[] buffer = baos.toByteArray();
            baos.close();
            oos.close();
            DatagramPacket packet = new DatagramPacket(buffer, buffer.length,InetAddress.getLocalHost(), portnumber);
            is.send(packet);

            System.out.println( "patient name " + patientName );
            System.out.println( "Check In");
        }
        catch (Exception e){
            System.out.println("ERROR Cashier: " + e.getMessage() );
            e.printStackTrace();
        }
    }
}

这是我的接收器类...

class Reciever2 extends Thread {
    public Reciever2(){
        this.start();   //starts the thread
    }

    public void run(){
        try {
            DatagramSocket socket = new DatagramSocket(5700,InetAddress.getLocalHost());
            System.out.println( "Recieving" );   //prints when receiving a message

            while (true){
                byte[] data = new byte[1024];    //array of bytes
                DatagramPacket packet = new DatagramPacket(data,data.length);  
                socket.receive(packet);      //receives the packet
                ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); 
                ObjectInputStream ois =  new ObjectInputStream(bais);
                String s = (String) ois.readObject();   //reading the data
                bais.close();   //closes input stream
                ois.close();   //closes input stream

                System.out.println(s);
                theText.setText( s);   //displays message
            }
        }
        catch (Exception e){
            System.out.println("ERROR Cook: " + e.getMessage() );
            }
        }
    }
4

2 回答 2

1

您可能需要编写一个接收器类来进行测试,或者可以访问目标服务器以便观察变化。UDP 协议几乎是一种单向协议。

本指南可能有助于了解更多信息DatagramSockets- 它还有一个关于编写发送者和接收者的部分。 http://docs.oracle.com/javase/tutorial/networking/datagrams/index.html

于 2012-04-16T13:50:51.713 回答
0

您可以使用一种称为 Mocking 的技术。请参阅Java 的最佳模拟框架是什么?了解更多信息。

于 2012-04-16T13:54:49.357 回答