我正在尝试使用TCP连接在我的Android手机和微控制器(粒子光子,非常类似于Arduino)之间进行通信,其中手机是未连接到互联网的无线热点。
每当我试图让他们彼此连接时,我都可以让客户端(Android应用程序)连接到服务器(Photon)。 TCPClient助手类似乎陷入了
serverMessage = in.readLine();
在TCPClient助手类中。这是我的调试结果:
E/TCP Client: C: Connecting...
E/TCP Client: C: out2 = java.io.OutputStreamWriter@ca4d31b
E/TCP Client: C: out1 = java.io.BufferedWriter@3c624cb8
E/TCP Client: C: out0 = java.io.PrintWriter@378aea91
E/TCP Client: C: Sent.
E/TCP Client: C: Done.
E/TCP Client: C: received = java.io.BufferedReader@36c43df6
E/TCP Client: C: run = true
E/TCP Client: C: I got to the while loop!
因此,很明显辅助类在in.readLine()中的分解。代码要通过该行进行并显示收到的结果需要什么?
这是TCPClient.java:
import android.util.Log;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
public class TCPClient {
private String serverMessage;
public static final String SERVERIP = "192.168.43.157"; //your Photon (formerly computer) IP address
public static final int SERVERPORT = 23;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedWriter out1;
OutputStreamWriter out2;
BufferedReader in;
/**
* 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(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
out2 = new OutputStreamWriter(socket.getOutputStream());
out1 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: out2 = " + out2);
Log.e("TCP Client", "C: out1 = " + out1);
Log.e("TCP Client", "C: out0 = " + out);
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()));
Log.e("TCP Client", "C: received = " + in);
Log.e("TCP Client", "C: run = " + mRun);
//in this while the client listens for the messages sent by the server
while (mRun) {
Log.e("TCP Client", "C: I got to the while loop!");
serverMessage = in.readLine();
Log.e("TCP Client", "C: serverMessage = " + serverMessage);
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
} else {
serverMessage = null;
}
}
Log.e("TCP Client", "C: run = " + mRun);
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 {
public void messageReceived(String message);
}
}
为完整起见,这是我的光子固件:
SYSTEM_MODE(MANUAL);
TCPServer server = TCPServer(23);
TCPClient client;
int flag = 0;
void setup() {
WiFi.on();
WiFi.setCredentials("AndroidAP", "password");
WiFi.connect();
// Make sure your Serial Terminal app is closed before powering your device
Serial.begin(9600);
// Now open your Serial Terminal, and hit any key to continue!
// start listening for clients
server.begin();
}
void loop() {
if (client.connected()) {
if(flag == 0) {
server.write("200");
// Serial.println("200");
flag = 0;
Serial.println(WiFi.SSID());
Serial.println(WiFi.localIP());
delay(1000);
}
// echo all available bytes back to the client
while (client.available() > 0) {
server.write("200");
Serial.println("200");
}
} else {
// if no client is yet connected, check for a new connection
client = server.available();
}
}
这是我的MainActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private TCPClient mTcpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.send_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// connect to the server
new connectTask().execute("message1");
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
@Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
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);
Log.d("Message", message);
}
});
mTcpClient.run();
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("values", values[0]);
}
}
}
答案 0 :(得分:0)
对于其他任何出现并希望做类似事情的人,我最终得到了这段代码。
TCPClient.java
import android.util.Log;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import static android.R.id.message;
public class TCPClient {
private String serverMessage;
public static String buttonPushed;
public static final String SERVERIP = "192.168.43.157"; //your Photon (formerly computer) IP address
public static final int SERVERPORT = 23;
private OnMessageReceived mMessageListener = null;
private boolean mRun = false;
PrintWriter out;
BufferedWriter out1;
OutputStreamWriter out2;
OutputStream out3;
BufferedReader in;
/**
* 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(String message){
if (out != null && !out.checkError()) {
out.println(message);
Log.d("TCP Client", "Message: " + 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
out3 = socket.getOutputStream();
out2 = new OutputStreamWriter(socket.getOutputStream());
out1 = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.e("TCP Client", "C: out3 = " + out3);
Log.e("TCP Client", "C: out2 = " + out2);
Log.e("TCP Client", "C: out1 = " + out1);
Log.e("TCP Client", "C: out0 = " + out);
sendMessage(buttonPushed); //this was the key
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()));
Log.e("TCP Client", "C: received = " + in);
Log.e("TCP Client", "C: run = " + mRun);
//in this while the client listens for the messages sent by the server
while (mRun) {
Log.e("TCP Client", "C: I got to the while loop!");
serverMessage = in.readLine();
Log.e("TCP Client", "C: serverMessage = " + serverMessage);
new TCPClient(mMessageListener);
stopClient();
if (serverMessage != null && mMessageListener != null) {
//call the method messageReceived from MyActivity class
mMessageListener.messageReceived(serverMessage);
} else {
serverMessage = null;
}
}
Log.e("TCP Client", "C: run = " + mRun);
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();
Log.d("TCP Client", "Socket closed.");
serverMessage = null;
}
} 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 {
public void messageReceived(String message);
}
}
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
// private ListView mList;
// private ArrayList<String> arrayList;
// private MyCustomAdapter mAdapter;
private TCPClient mTcpClient;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button) findViewById(R.id.send_button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// connect to the server
TCPClient.buttonPushed = "Get range 1";
new connectTask().execute("");
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
@Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
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);
Log.d("Message", message);
}
});
mTcpClient.run();
return null;
}
@Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
Log.d("values", values[0]);
//in the arrayList we add the messaged received from server
// arrayList.add(values[0]);
// notify the adapter that the data set has changed. This means that new message received
// from server was added to the list
// mAdapter.notifyDataSetChanged();
}
}
}
光子代码:
SYSTEM_MODE(MANUAL);
TCPServer server = TCPServer(23);
TCPClient client;
void setup() {
WiFi.on();
WiFi.setCredentials("AndroidAP", "password");
WiFi.connect();
// Make sure your Serial Terminal app is closed before powering your device
Serial.begin(9600);
// Now open your Serial Terminal, and hit any key to continue!
// start listening for clients
server.begin();
}
void loop() {
if (client.connected()) {
// echo all available bytes back to the client
while (client.available() > 0) {
server.write("200\n");
Serial.println("200");
Serial.println(WiFi.SSID());
Serial.println(WiFi.localIP());
}
} else {
// if no client is yet connected, check for a new connection
client = server.available();
}
}