好吧,我读了很多问题但无法弄清楚。我遇到从 Android 应用程序收到的数据问题。基本上我想控制伺服系统。该代码有效,但应用程序发送到服务器的数据是在单独的行中接收的。是的,我知道我需要使用缓冲区,我进行了一些研究,但找不到向我的代码添加缓冲区的方法。 另外,我认为我不需要显示我的 Java 代码,因为它只是通过按钮单击发送的基本命令(向上、向下等字符串)。
...Python Code(Server)...
ctrCmd = ['Up','Down', 'ON', 'OFF']
...
...
while True:
print ("Waiting for connection")
tcpCliSock,addr = tcpSerSock.accept()
print ("...connected from :", addr)
try:
while True:
data = ''
data = tcpCliSock.recv(BUFSIZE).decode()
print("This",data)
if not data:
print ("No Data",data)
break
if data == ctrCmd[0]:
print("I am here")
Servomotor.ServoUp()
print ("Increase: ",Servomotor.cur_X)
#tcpCliSock.send("Servo Increases".encode())
if data == ctrCmd[1]:
Servomotor.ServoDown()
print ("Decrease: ",Servomotor.cur_X)
#tcpCliSock.send("Servo Decreases".encode())
if data == ctrCmd[2]:
Servomotor.ledOn()
print ("Led On")
#tcpCliSock.send("Led On".encode())
if data == ctrCmd[3]:
Servomotor.ledOff()
print ("Led Off")
# tcpCliSock.send("Led Off".encode())
except KeyboardInterrupt:
Servomotor.close()
GPIO.cleanup()
tcpSerSock.close();
我也不明白为什么它显示没有数据,即使它显示收到的数据? 请帮助我真的是一个菜鸟,正在努力学习。 谢谢!!
更新!! 在我更改了decode()建议后,
public class MainActivity extends AppCompatActivity {
//UI Element
Button btnUp;
Button btnDown;
Button btnLedOn;
Button btnLedOff;
EditText txtAddress;
/*TextView message;*/
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);
btnUp = (Button) findViewById(R.id.btnUp);
btnDown = (Button) findViewById(R.id.btnDown);
btnLedOn = (Button) findViewById(R.id.btnLedOn);
btnLedOff = (Button) findViewById(R.id.btnLedOff);
txtAddress = (EditText) findViewById(R.id.ipAddress);
/*message = (TextView) findViewById(R.id.message);*/
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();
}
});
btnLedOn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getIPandPort();;
CMD = "ON";
Socket_AsyncTask cmd_led_on = new Socket_AsyncTask();
cmd_led_on.execute();
}
});
btnLedOff.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getIPandPort();
CMD = "OFF";
Socket_AsyncTask cmd_led_off = new Socket_AsyncTask();
cmd_led_off.execute();
}
});
}
public void getIPandPort()
{
String iPandPort = txtAddress.getText().toString();
Log.d("MYTEST","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);
//read input msg from server
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeBytes(CMD);
System.out.println(CMD);
dataOutputStream.close();
socket.close();
}catch (UnknownHostException e){e.printStackTrace();}catch (IOException e){e.printStackTrace();}
return null;
}
}
}
最佳答案
尝试一下:
socket = new java.net.Socket(inetAddress,MainActivity.wifiModulePort);
//read input msg from server
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeChars(CMD);
System.out.println(CMD);
dataOutputStream.close();
socket.close();
如果这会增加额外的空格,那么最简单的解决方案是继续使用 writeutf 并在服务器端对数据进行子串
socket = new java.net.Socket(inetAddress,MainActivity.wifiModulePort);
//read input msg from server
DataOutputStream dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataOutputStream.writeUTF(CMD);
System.out.println(CMD);
dataOutputStream.close();
socket.close();
在服务器端:
data = tcpCliSock.recv(BUFSIZE).decode()
data = data[2:]
引自 Javadoc:
Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. If no exception is thrown, the counter written is incremented by the total number of bytes written to the output stream. This will be at least two plus the length of str, and at most two plus thrice the length of str.
关于java - Python(服务器)从Java(客户端)接收数据在单独的行中..(TCP),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56146955/