真的很简单的TCP客户端

时间:2016-07-02 17:30:40

标签: android tcp

我希望我的应用输入我服务器的网址,例如http://192.168.1.8/和端口,例如1234。 当我的服务器收到TCP请求消息时,它会发回一个文件(服务器已经实现)。

我认为我不需要像AsyncTask那样复杂的东西,因为我不想保持连接。从服务器接收答案,我的连接必须关闭。

对前进方式或提示的任何指示都表示高度赞赏。

5 个答案:

答案 0 :(得分:31)

这是一个简单的TCP客户端,它使用我根据this tutorial中的代码工作的套接字(教程的代码也可以找到in this GitHub repository)。

请注意,此代码适用于在客户端和服务器之间来回发送字符串,通常采用JSON格式。

这是TCP客户端代码:

import android.util.Log;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

public class TcpClient {

    public static final String TAG = TcpClient.class.getSimpleName();
    public static final String SERVER_IP = "192.168.1.8"; //server IP address
    public static final int SERVER_PORT = 1234;
    // message to send to the server
    private String mServerMessage;
    // sends message received notifications
    private OnMessageReceived mMessageListener = null;
    // while this is true, the server will continue running
    private boolean mRun = false;
    // used to send messages
    private PrintWriter mBufferOut;
    // used to read messages from the server
    private BufferedReader mBufferIn;

    /**
     * Constructor of the class. OnMessagedReceived listens for the messages received from server
     */
    public TcpClient(OnMessageReceived listener) {
        mMessageListener = listener;
    }

    /**
     * Sends the message entered by client to the server
     *
     * @param message text entered by client
     */
    public void sendMessage(final String message) {
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                if (mBufferOut != null) {
                    Log.d(TAG, "Sending: " + message);
                    mBufferOut.println(message);
                    mBufferOut.flush();
                }
            }
        };
        Thread thread = new Thread(runnable);
        thread.start();
    }

    /**
     * Close the connection and release the members
     */
    public void stopClient() {

        mRun = false;

        if (mBufferOut != null) {
            mBufferOut.flush();
            mBufferOut.close();
        }

        mMessageListener = null;
        mBufferIn = null;
        mBufferOut = null;
        mServerMessage = null;
    }

    public void run() {

        mRun = true;

        try {
            //here you must put your computer's IP address.
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

            Log.d("TCP Client", "C: Connecting...");

            //create a socket to make the connection with the server
            Socket socket = new Socket(serverAddr, SERVER_PORT);

            try {

                //sends the message to the server
                mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);

                //receives the message which the server sends back
                mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));


                //in this while the client listens for the messages sent by the server
                while (mRun) {

                    mServerMessage = mBufferIn.readLine();

                    if (mServerMessage != null && mMessageListener != null) {
                        //call the method messageReceived from MyActivity class
                        mMessageListener.messageReceived(mServerMessage);
                    }

                }

                Log.d("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'");

            } catch (Exception e) {
                Log.e("TCP", "S: Error", e);
            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
            }

        } catch (Exception e) {
            Log.e("TCP", "C: Error", e);
        }

    }

    //Declare the interface. The method messageReceived(String message) will must be implemented in the Activity
    //class at on AsyncTask doInBackground
    public interface OnMessageReceived {
        public void messageReceived(String message);
    }

}

然后,在Activity:

中声明一个TcpClient作为成员变量
public class MainActivity extends Activity {

    TcpClient mTcpClient;

    //............

然后,使用AsyncTask连接到您的服务器并在UI线程上接收响应(请注意,从服务器接收的消息是在AsyncTask中的onProgressUpdate()方法覆盖中处理的):

public class ConnectTask extends AsyncTask<String, String, TcpClient> {

    @Override
    protected TcpClient doInBackground(String... message) {

        //we create a TCPClient object
        mTcpClient = new TcpClient(new TcpClient.OnMessageReceived() {
            @Override
            //here the messageReceived method is implemented
            public void messageReceived(String message) {
                //this method calls the onProgressUpdate
                publishProgress(message);
            }
        });
        mTcpClient.run();

        return null;
    }

    @Override
    protected void onProgressUpdate(String... values) {
        super.onProgressUpdate(values);
        //response received from server
        Log.d("test", "response " + values[0]);
        //process server response here....

}

要开始与服务器的连接,请执行AsyncTask:

new ConnectTask().execute("");

然后,向服务器发送消息:

//sends the message to the server
if (mTcpClient != null) {
    mTcpClient.sendMessage("testing");
}

您可以随时关闭与服务器的连接:

if (mTcpClient != null) {
    mTcpClient.stopClient();
}

答案 1 :(得分:5)

感谢您的代码。在我的情况下,我无法接收数据,因为我没有使用基于行的协议。 我写了一个替代实现,它适用于我的特定服务器设置:

  1. 在TcpClient.java文件中,&#34; run()&#34;命令你应该用下面的代码片段替换

    public void run(){

    mRun = true;
    
    try {
        InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
        Log.e("TCP Client", "C: Connecting...");
        Socket socket = new Socket(serverAddr, SERVER_PORT);
        try {
            mBufferOut = new PrintWriter(socket.getOutputStream());
            Log.e("TCP Client", "C: Sent.");
            mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            int charsRead = 0; char[] buffer = new char[1024]; //choose your buffer size if you need other than 1024
    
            while (mRun) {
                charsRead = mBufferIn.read(buffer);
                mServerMessage = new String(buffer).substring(0, charsRead);
                if (mServerMessage != null && mMessageListener != null) {
                    mMessageListener.messageReceived(mServerMessage);}
                mServerMessage = null;
            }
            Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + mServerMessage + "'"); 
    
  2. //其余代码没问题,见原文

    1. 您的MainActivity.java中的doInBackgroud将收到的消息发布到onProgressUpdate,您可以将其显示在其他对象中,例如TextView的

      @Override
      protected void onProgressUpdate(String... values) {
              super.onProgressUpdate(values);
              Log.d("test", "response " + values[0]);
              response.setText(response.getText() + "/n" +values[0]);
      } 
      
    2. //&#34;响应&#34;是函数中声明的TextView对象

      public class MainActivity extends AppCompatActivity {
      TextView response; //...so on
      

      和功能

      protected void onCreate(Bundle savedInstanceState) { response = (TextView) findViewById(R.id.textView); //..so on

答案 2 :(得分:1)

首先在android清单中为您的应用授予互联网权限

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

您可以使用AsyncTask轻松发送请求并接收文件

    public void send_request() {
    send_request sr = new send_request();
    sr.execute();
}

class send_request extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... voids) {
        try {             /*note : ip address must be in Quotation mark*/
                          /*note : port doesn't need to be inside the Quotation mark*/
            Socket s = new Socket(/*ip address :*/"192.168.1.8",/*port :*/ 1234);
            PrintWriter printWriter = new PrintWriter(s.getOutputStream());
            printWriter.write("your message");
            printWriter.flush();
            printWriter.close();
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    public void onPostExecute(final String Data) {
        /*Data is what you receive from your server*/
        Log.e("my_Data","Data is : " + Data);
    }
}

答案 3 :(得分:0)

在TcpClient中尝试以下代码:

 public void run() {
        mRun = true;
        try {
            InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
            Log.e("TCP Client", "C: Connecting...");
            Socket socket = new Socket(serverAddr, SERVER_PORT);
            try {
                mBufferOut = new PrintWriter(socket.getOutputStream());
                Log.e("TCP Client", "C: Sent.");
                mBufferIn = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                int charsRead = 0; char[] buffer = new char[2024]; //choose your buffer size if you need other than 1024
                while (mRun) {
                    charsRead = mBufferIn.read(buffer);
                    mServerMessage = new String(buffer).substring(0, charsRead);
                    if (mServerMessage != null && mMessageListener != null) {
                        Log.e("in if---------->>", " Received : '" + mServerMessage + "'");
                    }
                    mServerMessage = null;
                }
                Log.e("-------------- >>", " Received : '" + mServerMessage + "'");
            } catch (Exception e) {
                Log.e("TCP", "S: Error", e);
            } finally {
                //the socket must be closed. It is not possible to reconnect to this socket
                // after it is closed, which means a new socket instance has to be created.
                socket.close();
                Log.e("-------------- >>", "Close socket " );
            }

        } catch (Exception e) {
            Log.e("TCP", "C: Error", e);
        }

    }

它正常工作。上面其他代码中的这一行会导致错误。

  

mMessageListener.messageReceived(mServerMessage);

删除此行,您的应用程序运行良好。您也可以监视您在android studio中的登录。

您可以在Golang中的服务器上使用此代码。这是我的服务器:

package main

import (
    "bufio"
    "flag"
    "fmt"
    "net"
    "strconv"
)
var addr = flag.String("addr", "", "The address to listen to; default is \"\" (all interfaces).")
var port = flag.Int("port", 37533, "The port to listen on; default is 37533.")
func main() {
    flag.Parse()
    fmt.Println("Starting server...")
    src := *addr + ":" + strconv.Itoa(*port)
    listener, _ := net.Listen("tcp", src)
    fmt.Printf("Listening on %s.\n", src)

    defer listener.Close()

    for {
        conn, err := listener.Accept()
        if err != nil {
            fmt.Printf("Some connection error: %s\n", err)
        }
        go handleConnection(conn)
    }
}

func handleConnection(conn net.Conn) {
    remoteAddr := conn.RemoteAddr().String()
  LocalAddr :=conn.LocalAddr().String()

  fmt.Println("Client LocalAddr  " + LocalAddr)
    fmt.Println("Client connected from " + remoteAddr)
    scanner := bufio.NewScanner(conn)
    for {
        ok := scanner.Scan()

        if !ok {
            break
        }

        handleMessage(scanner.Text(), conn)
    }
    fmt.Println("Client at " + remoteAddr + " disconnected.")
}

func handleMessage(message string, conn net.Conn) {
    fmt.Println("> " + message)
    if len(message) > 0 {
    conn.Write([]byte("This is from Golang.\n"))
    fmt.Println("----------> we send it....")
    }
}

答案 4 :(得分:0)

最终的部署环境是什么?您的代码指向本地IP。当您将其部署到真实的服务器环境时,事情可能会改变吗? 如果在托管服务器中启动此代码,请注意NAT问题。这样您将无法获取数据包。 考虑使用更复杂的协议(例如Socket.io可以提供帮助)