Socket.receive只执行一次

时间:2018-04-23 00:51:58

标签: java

DatagramSocket只接收第一个数据包。

正如你所看到的,我创建了无限循环,它应该返回类型文本。 我只收到第一行 - 问题在哪里?

(connect是我的远程服务器的命令)

public class Main {
public static void main(String[] args) {
    Main main = new Main();
    try {
        main.setupConnection(InetAddress.getByName("145.239.92.199"), 6969, "Szuja");
        main.socket = new DatagramSocket();
        Scanner sc = new Scanner(System.in);
        while(true) {
            main.wyslijPakiet(sc.nextLine());
        }
    }catch(Exception e) {
        e.printStackTrace();
    }
}

private DatagramSocket socket;
private InetAddress adresKonsultantow;
private int port;

private void setupConnection(InetAddress adress, int port, String nickname) {
    this.adresKonsultantow = adress;
    this.port = port;
    if(socket != null)
        socket.close();
    try {
        socket = new DatagramSocket();
        socket.connect(adresKonsultantow, port);
    } catch (SocketException e1) {
        e1.printStackTrace();
    }
    wyslijPakiet("\\connect\\" + nickname);
    Thread thread = new Thread(() -> {
        try {
            while(!Thread.currentThread().isInterrupted()) {                    
                byte[] bufor = new byte[1024];
                DatagramPacket packet = new DatagramPacket(bufor, bufor.length);
                socket.setReuseAddress(true);
                socket.receive(packet);
                String wiadomosc = new String(bufor);
                int finIndex = wiadomosc.indexOf("\\e");
                if(finIndex <= 0)
                    continue;
                wiadomosc = wiadomosc.substring(0, finIndex);
                System.out.println("REC: " + wiadomosc);
            }
        } catch(Exception e) {
            e.printStackTrace();
        }
    });

public void wyslijPakiet(String wiadomosc) {
    try {
        wiadomosc += "\\e";
        byte[] dane = wiadomosc.getBytes();
        DatagramPacket pakiet = new DatagramPacket(dane, 0, dane.length, adresKonsultantow, port);
        socket.send(pakiet);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

private void flushText(String text) {
    wyslijPakiet(text);
}

}

0 个答案:

没有答案