送信者クラスと受信者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();
}
}
}
そして、これは私のReceiverクラスです...
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() );
}
}
}