我怎么能在循环中得到字符串

时间:2013-10-03 04:43:55

标签: java udp java-server

我有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没有, 我怎么能在声明中得到String Hasil而真(真)?

2 个答案:

答案 0 :(得分:0)

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

    while(true){
while(hasil==null){
}
}

答案 1 :(得分: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
    }
}
是的,我知道风格很难看;)