5

我为 udp 服务器编写了简单的方法:

 private void runUdpServer() {
        String message;
        byte[] lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
        DatagramPacket packet = new DatagramPacket(lmessage, lmessage.length);
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(UDP_SERVER_PORT);
            socket.receive(packet);
            message = new String(lmessage, 0, packet.getLength());
            textMessage.setText(message);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

    }

我怎样才能让这个服务器运行并收听消息。我在 onCreate 中使用这个方法,但是当我从客户端发送消息时,我看到了这条消息,但是当我发送第二条消息时,我没有看到第二条消息。只有第一条消息。我怎样才能收到新消息?

编辑:这是我现在的代码:

@SuppressLint("NewApi")
public class Server extends Activity {

    private static final int UDP_SERVER_PORT = 2004;
    private static final int MAX_UDP_DATAGRAM_LEN = 1500;
    private TextView textMessage;
    private RunServerInThread runServer = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server);

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
          }

        textMessage = (TextView) findViewById(R.id.messageText);
        runServer = new RunServerInThread();
        runServer.start();
    }
    private Runnable updateTextMessage = new Runnable() {
        public void run() {
            if (runServer == null) return;
            textMessage.setText(runServer.getLastMessage());
        }
    };


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.server, menu);
        return true;
    }


    private void runUdpServer() {
        String message;
        byte[] lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
        DatagramPacket packet = new DatagramPacket(lmessage, lmessage.length);
        DatagramSocket socket = null;
        try {
            socket = new DatagramSocket(UDP_SERVER_PORT);
            socket.receive(packet);
            message = new String(lmessage, 0, packet.getLength());
            textMessage.setText(message);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                socket.close();
            }
        }

    }

    private class RunServerInThread extends Thread{
        private boolean keepRunning = true;
        private String lastmessage = "";

        @Override
        public void run() {
            String message;
            byte[] lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
            DatagramPacket packet = new DatagramPacket(lmessage, lmessage.length);
            DatagramSocket socket = null;
            while(keepRunning){
            try {
                socket = new DatagramSocket(UDP_SERVER_PORT);
                socket.receive(packet);
                message = new String(lmessage, 0, packet.getLength());
                textMessage.setText(message);
            } catch (SocketException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (socket != null) {
                    socket.close();
                }
            }
        }
        }

       public String getLastMessage() {
            return lastmessage;
        }
    }
}

我得到错误:

05-30 12:18:48.562: E/AndroidRuntime(17987): FATAL EXCEPTION: Thread-1233
05-30 12:18:48.562: E/AndroidRuntime(17987): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.view.ViewRootImpl.checkThread(ViewRootImpl.java:4746)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.view.ViewRootImpl.requestLayout(ViewRootImpl.java:823)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.view.View.requestLayout(View.java:15469)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.view.View.requestLayout(View.java:15469)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.view.View.requestLayout(View.java:15469)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.view.View.requestLayout(View.java:15469)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.widget.RelativeLayout.requestLayout(RelativeLayout.java:318)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.view.View.requestLayout(View.java:15469)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.widget.TextView.checkForRelayout(TextView.java:6368)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.widget.TextView.setText(TextView.java:3622)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.widget.TextView.setText(TextView.java:3480)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at android.widget.TextView.setText(TextView.java:3455)
05-30 12:18:48.562: E/AndroidRuntime(17987):    at pl.udpconnection.server.Server$RunServerInThread.run(Server.java:89)

我该如何解决这个问题?

4

1 回答 1

10

将你拥有的代码放入一个循环中,并将这个循环放入它自己的线程中,这样它就不会阻塞 UI 线程。

使用 runOnUiThread() 从这个新线程更新 UI。

例子:

private MyDatagramReceiver myDatagramReceiver = null;

protected void onResume() {
    myDatagramReceiver = new MyDatagramReceiver();
    myDatagramReceiver.start();
}

protected void onPause() {
    myDatagramReceiver.kill();
}

private class MyDatagramReceiver extends Thread {
    private boolean bKeepRunning = true;
    private String lastMessage = "";

    public void run() {
        String message;
        byte[] lmessage = new byte[MAX_UDP_DATAGRAM_LEN];
        DatagramPacket packet = new DatagramPacket(lmessage, lmessage.length);

        try {
            DatagramSocket socket = new DatagramSocket(UDP_SERVER_PORT);

            while(bKeepRunning) {
                socket.receive(packet);
                message = new String(lmessage, 0, packet.getLength());
                lastMessage = message;
                runOnUiThread(updateTextMessage);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }

        if (socket != null) {
            socket.close();
        }
    }

    public void kill() { 
        bKeepRunning = false;
    }

    public String getLastMessage() {
        return lastMessage;
    }
}

private Runnable updateTextMessage = new Runnable() {
    public void run() {
        if (myDatagramReceiver == null) return;
        textMessage.setText(myDatagramReceiver.getLastMessage());
    }
};
于 2013-05-25T19:44:11.277 回答