简体   繁体   中英

Send data over TCP from android app

I am trying to send data from android app Client class 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());
        }

    }
}

Use CClient class in activity to create connection and send data. Here is activity code

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");
    }

}

Problem: recive only one message from client (C# server, without any errors) and next messages wont sent.

This code works. I had to add a simple button to trigger the proc_Login call, I tested with

netcat -l -p 8546
on my server (debian), I got 5 'asaadsasdasd' each time I pressed the button. (I used the port 8546 because it was already opened on my firewall).

Of course I added

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

in the AndroidManifest.xml file.

Maybe your server code closes the socket after receiving a line.

Note also you don't need a Thread, an AsyncTask would be more appropriate, though for the example it works.

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()); } } } 

You are never cleaning up the connection to the server. You need to close these output stream once you flush the stream.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM