gpt4 book ai didi

android - 真正简单的 TCP 客户端

转载 作者:IT老高 更新时间:2023-10-28 23:38:35 26 4
gpt4 key购买 nike

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

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

非常感谢任何有关前进方向或提示的指示。

最佳答案

这是一个简单的 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();
}

关于android - 真正简单的 TCP 客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38162775/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com