晚上好,我试图将文本数据从mainactivity的textview传递到client.class(tcp client)并将其设置为另一个字符串(实际上,我在mainactivity的textview中传递ip集,并尝试将其加载到client.class中),但当我试图用toast将其可视化时(对于测试,如果我传递了变量,则会出现类似这样的情况)
这里是客户代码:
public class Client {
static Intent intent = getIntent();
static String getIp = intent.getExtra("key");
private String serverMessage;
public static final String SERVERIP = getIp; //your computer IP address
public static final int SERVERPORT = 4444;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
MainActivity main;
PrintWriter out;
BufferedReader in;
/**
* Constructor of the class. OnMessagedReceived listens for the messages received from server
*/
public Client(OnMessageReceived listener) {
mMessageListener = listener;
}
/**
* Sends the message entered by client to the server
* @param message text entered by client
*/
public void sendMessage(String message){
if (out != null && !out.checkError()) {
out.println(message);
out.flush();
}
}
public void stopClient(){
mRun = false;
}
public void run() {
mRun = true;
try {
//here you must put your computer's IP address.
InetAddress serverAddr = InetAddress.getByName(SERVERIP);
Log.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVERPORT);
try {
//send the message to the server
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: Sent.");
Log.e("TCP Client", "C: Done.");
//receive the message which the server sends back
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//in this while the client listens for the messages sent by the server
while (mRun) {
serverMessage = in.readLine();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
}
serverMessage = null;
}
Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'");
} 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 MyActivity
//class at on asynckTask doInBackground
public interface OnMessageReceived {
void messageReceived(String message);
}
}
主要活动:
Intent i = new Intent(MainActivity.this, Client.class);
i.putExtra("STRING_I_NEED", String.valueOf(indr));
1条答案
按热度按时间wfveoks01#
在你身上
MainActivity
这样做:在你的
Client class
执行以下操作:你能做到的
Toast
就像:另一个选择是将ip地址保存在
SharedPreferences
把它拿回来Client class
或者您可以创建一个带有返回值的静态方法,然后您可以在Client class
通过类名。