gpt4 book ai didi

java - 测试DatagramSockets的传输

转载 作者:太空宇宙 更新时间:2023-11-04 08:17:29 24 4
gpt4 key购买 nike

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

最佳答案

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

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

关于java - 测试DatagramSockets的传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10175336/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com