安卓 TCP 客户端.服务器只在进程停止后接收消息 [英] Android TCP Client. Server only receives messages after process is stopped

查看:25
本文介绍了安卓 TCP 客户端.服务器只在进程停止后接收消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 Java 编写的简单 TCP 服务器,我正在尝试为 Android 编写一个简单的 TCP 客户端,它将与运行在本地机器上的 TCP 服务器进行通信.

I have simple TCP server written in Java, and I'm trying to write a simple TCP client for Android that will communicate with the TCP server running on the local machine.

我可以让服务器接收消息,但奇怪的是,它仅在我通过 Eclipse 中的设备"窗口停止应用程序进程后才接收消息.

I can get the server to receive messages, but oddly it is only receiving the message AFTER I stop the Application process through the "Devices" window in Eclipse.

在 Android 客户端上,我有一个主 UI 线程,其中包含用于输入 IP 地址和端口号的字段(这一切正常,所以我不包括它的代码).当连接按钮被点击时,它会启动一个新的 ASyncTask 来完成 TCP 套接字工作.

On the Android client, I have the main UI thread which contains fields to enter the IP address and Port number(this all works fine so I am not including the code for it). When the connect button is clicked, it starts a new ASyncTask to do the TCP socket work.

这是 ConnectionTask 类的 doInBackground 方法的代码:

Here is the code for the ConnectionTask class's doInBackground method:

    protected Void doInBackground(Void... params) 
    {   
    String authMessage = "Authorize";
    boolean connected=false;
    try 
    {           
        Socket clientSocket = new Socket();
        SocketAddress serverAddress = new InetSocketAddress(address,port);
        Log.v("Connection Thread", serverAddress.toString());
        clientSocket.connect(serverAddress, 15);
        if(clientSocket.isConnected())
        {
            connected = true;
            Log.v("Connection Thread", "Connection Successful");
            DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
            BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            outToServer.writeBytes(authMessage);
            Log.v("Connection Thread", "Sent Auth Message");
            String response = inFromServer.readLine();

            Log.v("TCP Client", "Response: " + response);
            hash = computeHash(response.getBytes());
            //send the computed hash to the server
            outToServer.writeBytes(hash);
            outToServer.close();
            inFromServer.close();
            clientSocket.close();
        }
        else
        {
            Log.v("Connection Thread", "Not Connected yet...");
        }
    } 
    catch (Exception e) 
    {
        Log.v("Connection Thread", e.getMessage());
    }   
    return null;
}

当我按下连接按钮时,在模拟器中我看到了Sent Auth Message"的日志,但我的服务器没有收到消息Authorize",直到我通过 DDMS 终止进程.

When I press the connect button, in the emulator I see the logs up to "Sent Auth Message" but my server does not receive the message "Authorize" until I kill the process through DDMS.

这是服务器代码:

    public class Server
{
       private static SecureRandom random = new SecureRandom();
       public static void main(String argv[]) throws Exception
       {
             String rawClientMessage,lcClientMessage;
             ServerSocket welcomeSocket = new ServerSocket(5000);
             System.out.println("Starting Server...");
             while(true)
             {
                Socket connectionSocket = welcomeSocket.accept();
                BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream()));
                DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
                rawClientMessage = inFromClient.readLine();
                if(rawClientMessage!=null)
                {
                    lcClientMessage = rawClientMessage.toLowerCase() + '
';
                    System.out.println("Received Message! Contents: " + rawClientMessage);
                    if(lcClientMessage=="authorize")
                    {
                        System.out.println("Received auth request message, generating key...");
                        String key = generateKey();
                        //send key back
                        outToClient.writeBytes(key);
                        System.out.println("Key sent!");
                    }
                }
                try
                {
                    inFromClient.close();
                    outToClient.close();
                    connectionSocket.close();
                }
                catch(Exception e)
                {
                    System.out.println(e.getMessage());
                }
             }
       }

       private static String generateKey()
       {
             return new BigInteger(130, random).toString(32);
       }
}

这是发生的事情的分步总结:

Here is a step by step summary of what happens:

  1. 我启动服务器(它阻止等待连接并读取服务器已启动...")
  2. 我在 Android 客户端中输入 192.168.0.100 端口 5000 并点击连接"按钮
  3. 点击后创建 ASyncTask,上面列出了我的套接字代码
  4. 尚未在服务器控制台上收到任何消息...
  5. (我可以再次按下连接,什么也不会发生)(LogCat 还会读取发送身份验证消息"日志)
  6. 我通过 Eclipse 设备窗口终止了模拟器上的进程
  7. 服务器控制台打印:收到消息!内容:授权(如果我点击连接两次,消息会显示两次)

基本上,它似乎正在存储消息,并在程序关闭后将它们全部发送到网络上.

Basically it seems like it's storing the message and is letting them all out onto the wire after the close of the program.

感谢任何帮助,谢谢!可以发布更多代码,包括主 UI 线程和扩展 ASyncTask 的 ConnectionTask 类的其余部分(如果需要).

Any help is appreciated, thanks! Can post more code including main UI thread and rest of ConnectionTask class which extends ASyncTask (if needed).

谢谢!

推荐答案

你在读台词,但不是在写台词.readLine() 会阻塞直到它收到一个行终止符,而你永远不会发送一个.由于您接收的数据是二进制的,因此无论如何您都不应该尝试使用 readLine() 读取它.重新考虑您的数据流.

You are reading lines but you aren't writing lines. readLine() will block until it receives a line terminator, and you are never sending one. And as the data you are receiving is binary, you shouldn't be trying to read it with readLine() anyway. Reconsider your data streams.

这篇关于安卓 TCP 客户端.服务器只在进程停止后接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆