Тема: Не завершується програма
Добрий день зіткнувся з проблемою при написанні сервера і клієнта на UDP.
Програма доходить до кінця функції мейн але не завершується.
Використовую 2 потоки ну і головний.
Код:
Мейн
public class Main {
public static void main(String[] args) {
final int PORT = 7771;
ExecutorService executorService = Executors.newFixedThreadPool(2);
Thread thread = null, thread1 = null;
Exchanger<String> exchanger = new Exchanger<>();
try {
executorService.submit(new UDPServer(PORT, exchanger));
executorService.submit(new MessageHandler(System.out, exchanger));
} catch (SocketException e) {
e.printStackTrace();
}
BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in));
try {
DatagramSocket clientSocket = new DatagramSocket();
InetAddress ipAddress = InetAddress.getByName("localhost");
while(true){
byte[] sendData = new byte[1024];
System.out.println("Enter text: ");
String sentence = inFromUser.readLine();
if(sentence.equals("quit")) {
executorService.shutdown();
break;
}
sendData = sentence.getBytes();
DatagramPacket datagramPacket = new DatagramPacket(sendData, sendData.length, ipAddress, PORT);
clientSocket.send(datagramPacket);
}
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Class UDPServer
public class UDPServer extends Thread {
private DatagramSocket datagramSocket = null;
private DatagramPacket datagramPacket = null;
private byte[] recieveData;
private Exchanger<String> exchanger;
UDPServer(int port, Exchanger ex) throws SocketException {
super();
datagramSocket = new DatagramSocket(port);
recieveData = new byte[1024];
datagramPacket = new DatagramPacket(recieveData, recieveData.length);
exchanger = ex;
}
public void run(){
try {
while(true) {
datagramSocket.receive(datagramPacket);
String sentence = new String(datagramPacket.getData());
InetAddress ipAddress = datagramPacket.getAddress();
int port = datagramPacket.getPort();
exchanger.exchange("{" + ipAddress.toString()
+ ":" + Integer.toString(port) + "} : " + sentence);
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
finally {
close();
}
}
public void close(){
datagramSocket.close();
}
}
Class MeessageHandler
public class MessageHandler extends Thread {
private Exchanger<String> exchanger;
private PrintStream printStream = null;
MessageHandler(PrintStream printStream, Exchanger ex){
exchanger = ex;
this.printStream = printStream;
}
public void run(){
try {
while(true) {
printStream.println(exchanger.exchange("ok"));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}