我正在从事一个IoT项目,并且想要在android客户端和python服务器之间进行通信。我已经在双方上编写了代码,但是连接没有建立。 enter image description here
这是python服务器端代码:
from socket import *
from time import ctime
#import RPi.GPIO as GPIO
ctrCmd = ['Up', 'Down']
host = ''
port = 5540
Buffsize = 1024
addr =(host,port)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(addr)
tcpSerSock.listen(5)
while True:
print ('waiting for connection')
tcpCliSock.addr = tcpSerSock.accept()
print ('Connected from :', addr)
while True:
data =''
data = tcpCliSock.recv(Buffsize)
if not data:
break
if data == ctrCmd[0]:
lock
if data == ctrCmd[1]:
unlock
和Android客户端代码:
package com.example.akhtar.check;
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 java.io.DataOutputStream;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
public class MainActivity extends AppCompatActivity {
Button on;
Button off;
Socket myAppSocket = null;
public static String ipadd = "192.168.40.51";
public static int port = 5540;
public static String CMD = "0";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
on = findViewById(R.id.butOn);
off = findViewById(R.id.butoff);
on.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CMD = "on";
Log.i("myApp", "no network");
Socket_AsyncTask CMD_lock = new Socket_AsyncTask();
Log.i("olamba", "kuni");
CMD_lock.execute();
Log.i("osha", "kuni");
}
});
off.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
CMD = "off";
Socket_AsyncTask CMD_lock = new Socket_AsyncTask();
CMD_lock.execute();
}
});
}
public class Socket_AsyncTask extends AsyncTask<Void,Void,Void>
{
Socket socket;
@Override
protected Void doInBackground(Void... voids) {
try{
InetAddress inetaddress = InetAddress.getByName(ipadd);
Log.i("raly", "no network");
socket = new java.net.Socket(inetaddress, port);
Log.i("supra", "no network");
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeByte(Integer.parseInt(CMD));
dataOutputStream.close();
socket.close();
}catch(UnknownHostException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}
return null;
}
}
}
暂时,我希望两者之间建立连接。