我想测试我的程序,它在发送者和接收者类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() );
}
}
}