Android tcp socket连接速度慢

时间:2016-01-30 10:29:43

标签: android sockets tcp delay lag

我已经在我的计算机上用java设置了一个服务器,而客户端就是我的Android手机。

我正在尝试模拟我的应用程序中的鼠标行为,但问题是即使在最初几分钟一切运行顺利,最终客户端和服务器之间存在巨大延迟。

服务器代码

    try {
        System.out.println(InetAddress.getLocalHost());

        serverSocket = new ServerSocket(4444); // Server socket
        serverSocket.setReceiveBufferSize(10000);
    } catch (IOException e) {
        System.out.println("Could not listen on port: 4444");
    }

    System.out.println("Server started. Listening to the port 4444");


        try {

            clientSocket = serverSocket.accept(); // accept the client connection
            System.out.println("connection initiated");
            DataInputStream din = new DataInputStream(clientSocket.getInputStream());

            DataOutputStream dout= new DataOutputStream(clientSocket.getOutputStream());

            /* do my things here */
            din.close();
            dout.close();
            clientSocket.close();
        } catch (IOException ex) {
                System.out.println("Problem in message reading "+ex);
            }

客户代码

    @Override
    protected Void doInBackground(Void... arg0) {

        Socket socket = null;

        try {
            //Inet4Address.getLocalHost().toString(); //InetAddress.getLocalHost().getHostAddress().toString();
            System.out.println(dstAddress);
            socket = new Socket(dstAddress, dstPort);
            socket.setSendBufferSize(10000);
            DataInputStream din = new DataInputStream(socket.getInputStream());
            dout = new DataOutputStream(socket.getOutputStream());

            dout.writeUTF(kappa);


            response = "sent to server";

            String msg = din.readUTF();
            response += msg;
            din.close();
            dout.close();
            socket.close();



        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            response = e.toString();
        }
        return null;
    }

(kappa是我每次修改的全局字符串。)

可能是这种情况?

1 个答案:

答案 0 :(得分:0)

问题解决了,我改为udp连接,现在没有延迟