У меня проблемы с моим java проектом с UDP. У меня есть основной проект и поток, и я хочу проверить, может ли поток отправлять данные в основной класс, а основной класс получил данные. У меня проблемы с тем, что иногда основной класс успешно получал данные, а иногда оставался в полученном методе, даже если поток находится в методе send Можете ли вы объяснить, как отправить данные друг от друга.
package TestPackage;
import static org.junit.Assert.*;
import java.net.*;
import org.junit.Before;
import org.junit.Test;
import Model.Acknowledgement;
import Model.Converter;
import Model.Network;
import Model.EventSubsystem.ElevatorEvent;
/*
* this test is used to see if the network class works
*
*/
public class TestNetwork {
Thread testSendBytes;
Thread testSendAcknowledgement;
Thread testRecived;
Converter converter;
Network network;
Network network2;
ElevatorEvent elevatorEvent;
/**
* this method is used to see if the network can sent bytes though and received the right elevator event
*/
@Test
public void testSendByteArray() {
testSendBytes = new Thread(new TestSendBytes(), "test send Bytes");
testSendBytes.start();
try {
network = new Network(InetAddress.getLocalHost(), 0, 80);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(1);
DatagramPacket packet = network.receive();
System.out.println(4);
byte[] bytes = packet.getData();
elevatorEvent = (ElevatorEvent) converter.convertByteToObject(bytes);
System.out.println(elevatorEvent.getId());
assertEquals(elevatorEvent.getId(), 8);
}
}
/*
* this thread is used to send bites back to the main class if it runs.
*/
class TestSendBytes implements Runnable {
Converter converter;
Network network;
public void run()
{
try {
network = new Network(InetAddress.getLocalHost(), 80, 0);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ElevatorEvent elevatorEvent = new ElevatorEvent(8, 7, null, null, 69);
byte[] elevatorEventBytes = converter.convertObjectToByte(elevatorEvent);
/*try {
Thread.sleep(8000);
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}*/
network.send(elevatorEventBytes);
}
}
package Model;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* This class creates a network connection for sending and receiving UDP packets.
*/
public class Network {
private InetAddress address;
private int sendPort;
private int receivePort;
private Thread send;
/**
* Constructor for the network class.
* @param a InetAddress
* @param sendPort Port number that will use when sending the packet.
* @param receivePort port number to receive packet.
*/
public Network(InetAddress a, int sendPort, int receivePort) {
this.address = a;
this.sendPort = sendPort;
this.receivePort = receivePort;
}
/**
* Receive UDP packets.
* @return DatagramPacket.
*/
public DatagramPacket receive() {
DatagramPacket packet = null;
try {
byte msg[] = new byte[ProjectConstants.MAX_MESSAGE_LENGTH];
DatagramSocket socket = new DatagramSocket(receivePort);
packet = new DatagramPacket(msg, msg.length);
System.out.println(2);
socket.receive(packet);
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
return packet;
}
/**
* Sends a network packet with bytes of array.
* @param acknowledgement
*/
public void send(byte[] acknowledgement) {
try {
/* it forms a packet to send back to the host sending the request */
DatagramPacket packet = new DatagramPacket(acknowledgement,
acknowledgement.length,
address, sendPort);
/* it creates a DatagramSocket to use to send this request */
DatagramSocket socket = new DatagramSocket();
System.out.println(3);
socket.send(packet);
socket.close();
} catch (IOException e) {
e.printStackTrace();
System.exit(1);
}
}
/**
* Sends a network packet with Acknowledgement object.
* @param acknowledgement
*/
public void send(Acknowledgement acknowledgement) {
send = new Thread("send_thread") {
public void run() {
try {
DatagramPacket dgpack = new DatagramPacket(
acknowledgement.getMessage(),
acknowledgement.getMessage().length,
address,
(acknowledgement.getPort() != -1) ? acknowledgement.getPort() : sendPort
);
DatagramSocket socket = new DatagramSocket();
System.out.println(3);
socket.send(dgpack);
socket.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
};
send.start();
}
}