如何在连接到套接字时通过单击按钮发送字符串?



我想在连接到服务器时通过按钮单击上的套接字发送数据。我尝试在我的ConnectTask类和TcpClient类中调用setOnClickListener,但它向我显示了一个错误。当我在ConnectTask中创建它时,它没有向我显示错误,但它不起作用。我该怎么做?以下是我的课程。

这是我的主要课程:

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.util.Log;
import android.widget.EditText;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity {
Button btn;
EditText edt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button);
edt=(EditText)findViewById(R.id.editText);
ConnectTask connectTask=new ConnectTask();
connectTask.execute("testing");
}
public class ConnectTask extends AsyncTask<String, String, TcpClient> {

@Override
protected TcpClient doInBackground(String... message) {
Log.d("TCP Client", "checking");
TcpClient mTcpClient;
//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....
}
}
}    

这是我的TcpClient类:

import android.app.Activity;
import android.content.Context;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
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;
import android.os.Handler;
import static android.os.Looper.*;
public class TcpClient extends MainActivity{
public static final String TAG = TcpClient.class.getSimpleName();
public static final String SERVER_IP = "10.0.2.2"; //server IP address
public static final int SERVER_PORT = 9000;
// 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 = true;
// used to send messages
private PrintWriter mBufferOut;
// used to read messages from the server
private BufferedReader mBufferIn;
Context context=getApplicationContext();
/**
* 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(SERVER_IP, SERVER_PORT);
if(socket.isConnected()){
Log.d("hati","connected");
}
try {
//sends the message to the server
mBufferOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
sendMessage("testing");
//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) must be implemented in the Activity
//class at on AsyncTask doInBackground
public interface OnMessageReceived {
public void messageReceived(String message);
}
}
  1. 将 TcpClient mTcpClient 移动到 MainActivity 类:

    public class MainActivity extends AppCompatActivity {
    Button btn;
    EditText edt;
    TcpClient mTcpClient;
    
  2. 从受保护的 TcpClient doInBackground 中删除 TcpClient mTcpClient;

    protected TcpClient doInBackground(String... message) {
    Log.d("TCP Client", "checking");
    // remove this line TcpClient mTcpClient
    
  3. 将操作侦听器添加到按钮并调用 tcpClient以发送消息

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn=(Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
    mTcpClient.senMessage("get Text from text box");
    }
    });
    edt=(EditText)findViewById(R.id.editText);
    ConnectTask connectTask=new ConnectTask();
    connectTask.execute("testing");
    

    }

public class TcpClient extensions MainActivity{

在扩展活动的类的名称中没有 Activity 是非常糟糕的。为了使您的代码更具可读性,您应该将其更改为

public class TcpClientActivity extends MainActivity{

然后你会得到

mTcpClient = new TcpClientActivity(new TcpClientActivity.OnMessageReceived() {

每个身体都会站起来哭泣:您不允许与new运算符实例化活动。

最新更新