从Android应用程序通过TCP发送数据

时间:2014-02-25 15:11:59

标签: java android tcp

我正在尝试从Android应用程序发送数据 客户端类src:

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class CClient    
implements Runnable     
{
    private Socket socket;
    private String ServerIP = "10.0.0.14";


    public void run()
    {
        try 
        {
            socket = new Socket("10.0.0.14", 16606);

        }
        catch(Exception e) 
        {
            System.out.print("Whoops! It didn't work!:");
            System.out.print(e.getLocalizedMessage());
            System.out.print("\n");
        }
    }

    public void Send(String s)
    {
        try
        {
            PrintWriter outToServer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
            outToServer.print(s + "\n");
            outToServer.flush();


        }
        catch (UnknownHostException e) {
            System.out.print(e.toString());
        } catch (IOException e) {
            System.out.print(e.toString());
        }catch (Exception e) {
            System.out.print(e.toString());
        }

    }
}

在活动中使用CClient类来创建连接并发送数据。 这是活动代码

import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;


public class Auth extends Activity {

    private ProgressBar mProgress;
    private TextView mTV;

    private CClient mClient;

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


        mProgress = (ProgressBar) findViewById(R.id.progressBar1);
        mTV =  (TextView) findViewById(R.id.textView4);

        mClient = new CClient();                
        Thread myThready = new Thread(mClient);
        myThready.start();  

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.auth, menu);
        return true;
    }

    public void proc_Login(View v)
    {

        for (int i=0; i<5; i++)
            mClient.Send("asaadsasdasd");
    }

}

问题:只收到来自客户端的一条消息(C#服务器,没有任何错误),下一条消息不会被发送。

2 个答案:

答案 0 :(得分:2)

此代码有效。我必须添加一个简单的按钮来触发proc_Login调用,我在我的服务器(debian)上用

netcat -l -p 8546
进行了测试,每次按下按钮我都得到5'asaadsasdasd'。 (我使用了端口8546,因为它已经在我的防火墙上打开了。)

当然我添加了

<uses-permission android:name="android.permission.INTERNET" />

在AndroidManifest.xml文件中。

也许您的服务器代码在收到一行后关闭套接字。

另请注意,您不需要Thread,AsyncTask会更合适,但是对于它可以运行的示例。

MainActivity.java:

package com.defranoux.testtcpsend;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

  private CClient mClient;

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

    mClient = new CClient();                
    Thread myThready = new Thread(mClient);
    myThready.start();

    Button button1 = (Button) findViewById(R.id.button1);
    button1.setOnClickListener(new OnClickListener() {

      @Override
      public void onClick(View arg0) {
        proc_Login(arg0);        
      }
    });    
  }


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
  }

  public void proc_Login(View v)
  {
      for (int i=0; i<5; i++)
          mClient.Send("asaadsasdasd");
  }

}

CClient.java:

package com.defranoux.testtcpsend;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;

public class CClient    
implements Runnable     
{
    private Socket socket;
    private String ServerIP = "<my server ip goes here>";
    private static final int ServerPort = 8546;

    @Override
    public void run()
    {
        try 
        {
            socket = new Socket(ServerIP, ServerPort);
        }
        catch(Exception e) 
        {
            System.out.print("Whoops! It didn't work!:");
            System.out.print(e.getLocalizedMessage());
            System.out.print("\n");
        }
    }

    public void Send(String s)
    {
        try
        {
            PrintWriter outToServer = new PrintWriter(
                new OutputStreamWriter(
                    socket.getOutputStream()));
            outToServer.print(s + "\n");
            outToServer.flush();


        }
        catch (UnknownHostException e) {
            System.out.print(e.toString());
        } catch (IOException e) {
            System.out.print(e.toString());
        }catch (Exception e) {
            System.out.print(e.toString());
        }

    }
}

答案 1 :(得分:0)

您永远不会清理与服务器的连接。刷新流后,需要关闭这些输出流。

outToServer.flush();
outToServer.close();