使用Android接收tcp消息

时间:2015-04-12 13:30:42

标签: android tcp

我正在开发一个远程控制应用程序来控制我的所有设备(电视,媒体中心等)我最初编写它以使用远程索尼API工作得很好但现在我想尝试通过我的网络控制设备。

我已经完成了使用SOAP请求的电视,现在我正在做我的媒体中心,这是一台PC。 我的问题是我可以发送媒体中心正确响应的命令(我可以看到使用Wireshark返回的响应)。发送的命令位于变量str和str1中。

我对Android编程很新,对IP知之甚少,所以我想知道是否有人能指出我正确的方向。

我正在使用API​​ 19(我是唯一一个使用该应用程序的人),目前它在发送我的TCP命令后会崩溃。我怀疑我做的事情很愚蠢。我的代码如下: -

public class MainActivity extends Activity
{
String success;
Button btnok;
TextView txtvwdata1;

MyTask objMyTask;

private Socket socket;
public Void result;

private static final int SERVERPORT = 8017;
private static final String URL = "192.168.1.95";


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnok = (Button)findViewById(R.id.btnok);
    txtvwdata1 = (TextView)findViewById(R.id.txtvwdata1);

    new Thread(new ClientThread()).start();

    btnok.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            objMyTask = new MyTask();
            objMyTask.execute();
        }
    });
}

class ClientThread implements Runnable
{
    @Override
    public void run()
    {
        try
        {
            InetAddress serverAddr = InetAddress.getByName(URL);
            socket = new Socket(serverAddr, SERVERPORT);
        } catch (UnknownHostException e1)
        {
            e1.printStackTrace();
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }
    }
}

class MyTask extends AsyncTask<Void, Void, String>
{
    @Override
    protected String doInBackground(Void... params)
    {
        try
        {
            String str = "\r\n{\"Type\":\"identify\",\"AppName\":null,\"Authenticate\":{\"AuthMethod\":\"userpass\",\"Password\":\"admin\",\"User\":\"admin\"},\"Description\":\"Android client for MediaPortal\",\"Name\":\"Steve\",\"Version\":\"1.0\"}\r\n";
            String str1 = "\r\n{\"Type\":\"playchannel\",\"ChannelId\":1315,\"StartFullscreen\":true}\r\n";

            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
            delay();
            out.println(str1);
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        //Get Response    
        InputStream is = null;
        // is= connection.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        String line;
        StringBuffer response = new StringBuffer(); 
        try {
            while((line = rd.readLine()) != null)
            {
                response.append(line);
                response.append('\r');
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        try {
            rd.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        Log.i("response", "" + response.toString());
        return response.toString();
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    protected String onPostExecute()
    {
        return null;
    }
}

public void delay()
{
    int i = 0;
    while(i < 100000)
    {
        i++;
    }
}
}

1 个答案:

答案 0 :(得分:0)

非常感谢你帮助greenapps,这解决了我的问题。完成更改后,您建议不要崩溃并获得响应。

private Socket socket=null;
is = socket.getInputStream(); 
response.append("\n");

这是我现在的代码: -

public class MainActivity extends Activity
{


String success;
Button btnok;
TextView txtvwdata1;

MyTask objMyTask;

public String result;

private Socket socket=null;

private static final int SERVERPORT = 8017;
private static final String URL = "192.168.1.95";


@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnok = (Button)findViewById(R.id.btnok);
    txtvwdata1 = (TextView)findViewById(R.id.txtvwdata1);

    new Thread(new ClientThread()).start();

    btnok.setOnClickListener(new OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            objMyTask = new MyTask();
            objMyTask.execute();
            txtvwdata1.setText(result);
        }
    });
}

class ClientThread implements Runnable
{
    @Override
    public void run()
    {
        try
        {
            InetAddress serverAddr = InetAddress.getByName(URL);
            socket = new Socket(serverAddr, SERVERPORT);
        } catch (UnknownHostException e1)
        {
            e1.printStackTrace();
        }
        catch (IOException e1)
        {
            e1.printStackTrace();
        }
    }
}

class MyTask extends AsyncTask<Void, Void, String>
{
    @Override
    protected String doInBackground(Void... params)
    {
        try
        {
            String str = "\r\n{\"Type\":\"identify\",\"AppName\":null,\"Authenticate\":{\"AuthMethod\":\"userpass\",\"Password\":\"admin\",\"User\":\"admin\"},\"Description\":\"Android client for MediaPortal\",\"Name\":\"aMPdroid\",\"Version\":\"1.1.3\"}\r\n";
            String str1 = "\r\n{\"Type\":\"playchannel\",\"ChannelId\":1315,\"StartFullscreen\":true}\r\n";

            PrintWriter out = new PrintWriter(new BufferedWriter(
                    new OutputStreamWriter(socket.getOutputStream())),
                    true);
            out.println(str);
            out.println(str1);
        }
        catch (UnknownHostException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        //Get Response    
        try
        {
            InputStream is= socket.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is));
            String line;
            StringBuffer response = new StringBuffer();
            try {
                int a = 1;
                while((line = rd.readLine()) != null)
                {
                    response.append(line);
                    response.append("\r\n");
                    Log.i("response", "" + response.toString());
                    if (a == 1)
                    {
                        break;
                    }
                    a++;
                }
                result = response.toString();
                return response.toString();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            try {
                rd.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        try
        {
            socket.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    @Override
    protected void onPreExecute()
    {
        super.onPreExecute();
    }

    protected String onPostExecute()
    {
        return null;
    }
}

}