Android的TCP客户端。服务器只处理停止后,接收消息 [英] Android TCP Client. Server only receives messages after process is stopped

查看:126
本文介绍了Android的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客户端,我有一个包含字段中输入IP地址和端口号(这一切工作正常,所以我不包括code吧)主UI线程。当点击连接按钮,它会启动一个新的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.

下面是code为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;
}

当我preSS连接按钮,在模拟器中我看到的日志,发送验证信息,但我的服务器没有收到消息授权,直到我通过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.

下面是服务器code:

Here is the server code:

    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() + '\n';
                    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. 我输入192.168.0.100端口是5000到Android客户端,然后点击连接按钮

  3. 的AsyncTask是建立在点击创建我的插座code上面列出

  4. 没有收到服务器控制台上还没有...

  5. (我可以preSS重新连接,也不会有事)(LogCat中还读取到发送验证信息的日志)

  6. 我杀模拟器过程中,通过Eclipse的设备窗口

  7. Server控制台打印:收到信!内容:授权(如果我点击连接两次显示两次消息)

基本上它好像它存储信息和程序结束后,让他们全力以赴在电线上。

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

任何帮助是AP preciated,谢谢!可以发布更多code,包括主UI线程和ConnectionTask类的其余部分延伸AsyncTask的(如果需要)。

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.

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

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