Android Socket编程延迟

时间:2016-04-16 21:08:04

标签: android multithreading sockets

我在PC上有一个客户端Android应用程序和一个服务器程序。在客户端应用程序中,我在我的Activity的onCreate()中启动一个新线程。在该线程中,有一个无限循环将消息发送到服务器。但有时延迟可达5秒。这是客户端的代码:

修改

new Thread(new Runnable() {
        public void run() {
            Socket socket = null;
            PrintWriter out = null;
            try {
                socket = new Socket(ip, 1755);
                out = new PrintWriter(socket.getOutputStream(), true);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while(true) {
                if(socket != null) {
                    out.println(msg);
                }
            }
        }
    }).start();

现在消息未送达。

2 个答案:

答案 0 :(得分:1)

参考此代码,

    import java.io.BufferedWriter;
    import java.io.IOException;
    import java.io.OutputStreamWriter;
    import java.io.PrintWriter;
    import java.net.InetAddress;
    import java.net.Socket;
    import java.net.UnknownHostException;

    /**
     * @author Krish
     */
    public class Client {


        public void connect() {
            new Thread(new ClientThread()).start();
        }


        public void disconnect() {
            try {
                socket.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }


        public void sendMessage(String msg) {
            try {
                PrintWriter out = new PrintWriter(new BufferedWriter(
                        new OutputStreamWriter(socket.getOutputStream())),
                        true);


           out.println(msg);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


    private Socket socket;

    class ClientThread implements Runnable {

        private static final int SERVERPORT = 6000;

        private static final String SERVER_IP = "10.0.2.15";


        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }

}

还可以找到优化技术

答案 1 :(得分:0)

可能是因为您正在创建无限量的套接字并发送。而不是创建一次并发送然后关闭或可能是网络问题。