我通过WiFi直接将手机连接到传感器。我应该连接到端口5001以获取传感器数据。我一直在设置TCP客户端时遇到问题,因此我可以打开端口并检索数据。我发现这篇帖子Really simple TCP client我复制粘贴了代码。
要测试我的代码,我使用应用程序“Simple Socket Tester”,我在另一部手机上启动IP地址为192.168.1.52,端口5001的服务器。我通过WiFi直接连接手机,成功连接后ConnectTask代码应该运行。但我得到“java.net.ConnectException:无法连接到/192.168.1.52(端口5001):连接失败:ETIMEDOUT(连接超时)”。为什么会这样?我做错了什么?。
修改:
我设法现在连接到服务器。但现在我无法看到我从服务器发送的消息。
以下是我正在做的详细演练,
我的TCP客户端代码:
public class TCPClient {
public static final String SERVER_IP = "192.168.1.52"; //your computer IP address
public static final int SERVER_PORT = 5001;
// 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(String message) {
if (mBufferOut != null && !mBufferOut.checkError()) {
mBufferOut.println(message);
mBufferOut.flush();
}
}
/**
* Close the connection and release the members
*/
public void stopClient() {
Log.i("Debug", "stopClient");
// send mesage that we are closing the connection
//sendMessage(Constants.CLOSED_CONNECTION + "Kazy");
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.e("TCP Client", "C: Connecting...");
//create a socket to make the connection with the server
Socket socket = new Socket(serverAddr, SERVER_PORT);
try {
Log.i("Debug", "inside try catch");
//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()));
// send login name
//sendMessage(Constants.LOGIN_NAME + PreferencesManager.getInstance().getUserName());
//sendMessage("Hi");
//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.e("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);
}
}
我的ConnectTask
public class ConnectTask extends AsyncTask<String, String, TCPClient> {
@Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object
TCPClient 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....
}
}
我的WiFi直接活动中启动ConnectTask的部分
public class WiFiDirectActivity extends Activity implements WifiP2pManager.ChannelListener, DeviceListFragment.DeviceActionListener {
...
@Override
public void connect(WifiP2pConfig config) {
config.groupOwnerIntent = 0;
manager.connect(channel, config, new WifiP2pManager.ActionListener()
{
@Override
public void onSuccess() {
// WiFiDirectBroadcastReceiver will notify us. Ignore for now.
new ConnectTask().execute("");
//sends the message to the server
if (mTCPClient != null) {
mTCPClient.sendMessage("testing");
}
}
@Override
public void onFailure(int reason) {
Toast.makeText(WiFiDirectActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});