0

我有 2 节课

头等舱

import java.io.IOException;
import java.net.*;

public class Udp {

    DatagramSocket socket = null;
    DatagramPacket inPacket = null; // recieving packet
    DatagramPacket outPacket = null; // sending packet
    byte[] inBuf, outBuf;
    InetAddress source_address = null;
    public String Hasil = null;
    String msg;
    final int PORT = 8888;

    public void received() {
    try {
        socket = new DatagramSocket(PORT);
        while (true) {
            System.out.println("Waiting for client...");

            // Receiving datagram from client
            inBuf = new byte[256];
            inPacket = new DatagramPacket(inBuf, inBuf.length);
            socket.receive(inPacket);

            // Extract data, ip and port
            int source_port = inPacket.getPort();
            source_address = inPacket.getAddress();
            msg = new String(inPacket.getData(), 0, inPacket.getLength());
            // System.out.println("Client " + source_address + ":" + msg);
            Hasil = msg;
            // Send back to client as an echo
            msg = reverseString(msg.trim());
            outBuf = msg.getBytes();
            outPacket = new DatagramPacket(outBuf, 0, outBuf.length,
                    source_address, source_port);
            socket.send(outPacket);
        }
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }

    System.out.println("Client " + source_address + ":" + msg);
}

private static String reverseString(String input) {
    StringBuilder buf = new StringBuilder(input);
    return buf.reverse().toString();
}}

和二等

public class main {
public static void main(String[] args) {
    Udp u = new Udp();
    u.received();
    System.out.println(u.Hasil + " " + u.source_address);
    }
}

为什么当我运行这个 porgram 时,udp 是启动的,但是 String Hasil 没有启动,我如何在语句 While (true) 中获取 String Hasil?

4

2 回答 2

0

您需要单独的线程:

public class Udp implements Runnable {
    boolean running = false;
    ...
        while(running) { // <-- this was your while (true) {
        ...
    @Override
    public void run {
        running = true
        received();
    }

    public void stop() {
        running = false;
    }
}

在你的主要

...
new Thread(u).start();
while(u.Hasil != null){
    try{
      Thread.currentThread().sleep(1);//sleep for 1 ms
    }
    catch(ItrerruptedException ie){
        //ignore
    }
}

是的,我知道这种风格很丑;)

于 2013-10-03T05:09:05.453 回答
0

你的字符串可能为空试试这个结构:

    while(true){
while(hasil==null){
}
}
于 2013-10-03T04:52:16.797 回答