我在python上有一个服务器,在Android上有一个客户端,我已经完成了向服务器发送CMD命令,功能服务器端将执行该命令,然后向客户端发送消息。现在我的问题是我不知道如何从服务器收到消息到我的Android客户端到目前为止这是我的代码,我真的希望你能救我们,非常感谢
public class MainActivity extends AppCompatActivity {
Button btnUp;
Button btnDown;
Button btnRight;
Button btnLeft;
Button btnStop;
EditText txtAddress;
Socket myAppSocket = null;
public static String wifiModuleIp = "";
public static int wifiModulePort = 0;
public static String CMD ="0";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtnum = (TextView) findViewById(R.id.tv_reply_from_server);
btnUp = (Button) findViewById(R.id.btnUp);
btnDown = (Button) findViewById(R.id.btnDown);
btnRight = (Button) findViewById(R.id.btnRight);
btnLeft = (Button) findViewById(R.id.btnLeft);
btnStop = (Button) findViewById(R.id.btnStop);
txtAddress = (EditText) findViewById(R.id.IPadd);
btnStop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getIpandPort();
CMD = "Stop";
Socket_AsyncTask cmd_increase_servo = new Socket_AsyncTask();
cmd_increase_servo.execute();
}
});
btnUp.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getIpandPort();
CMD = "Up";
Socket_AsyncTask cmd_increase_servo = new Socket_AsyncTask();
cmd_increase_servo.execute();
}
});
btnDown.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getIpandPort();
CMD = "Down";
Socket_AsyncTask cmd_increase_servo = new Socket_AsyncTask();
cmd_increase_servo.execute();
}
});
btnRight.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getIpandPort();
CMD = "Right";
Socket_AsyncTask cmd_increase_servo = new Socket_AsyncTask();
cmd_increase_servo.execute();
}
});
btnLeft.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getIpandPort();
CMD = "Left";
Socket_AsyncTask cmd_increase_servo = new Socket_AsyncTask();
cmd_increase_servo.execute();
}
});
}
public void getIpandPort()
{
String iPandPort = txtAddress.getText().toString();
Log.d("MY TEST","IP String:" + iPandPort);
String temp[] = iPandPort.split(":");
wifiModuleIp = temp[0];
wifiModulePort = Integer.valueOf(temp[1]);
Log.d("MY TEST","IP:" + wifiModuleIp);
Log.d("MY TEST ","PORT:" + wifiModulePort);
}
public class Socket_AsyncTask extends AsyncTask<Void, Void, Void>
{
Socket socket;
@Override
protected Void doInBackground(Void... params){
try{
InetAddress inetAddress = InetAddress.getByName(MainActivity.wifiModuleIp);
socket = new java.net.Socket(inetAddress,MainActivity.wifiModulePort);
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeBytes(CMD);
dataOutputStream.close();
socket.close();
}catch (UnknownHostException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}
return null;
}
}
}