我正在开展一个项目,应用程序和脚本之间的可靠和快速(100次/秒)通信非常重要。我已经在双方都实现了Socket通信,但是如果Android应用程序将数据发送到Python脚本,有时(从10开始1-2次),就会出现错误,并且Python脚本无法正确解析收到的数据。例如,重复发送FLAG::val1::val2::val3
或FLAG::val1
时会出现值错误。
这里我是如何实现Python套接字服务器的:
class Connection():
def __init__(self):
self.connected = False
def start_connention(self):
host = '192.168.42.1'
port = 8888
self.server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
#Bind socket to local host and port
try:
self.server.bind((host, port))
except socket.error, msg:
print 'Bind failed. Error code: ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
#Start listening on socket
self.server.listen(10)
print 'Socket now listening on ' + str(port)
self.connection, addr = self.server.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#Disable blocking
self.connection.settimeout(0.0)
self.connected = True
def read(self):
try:
data = self.connection.recv(4096).split("::")
except:
data = ["N"] #no data
return data
def send(self, message):
self.connection.sendall(message)
def close(self):
print("closing")
self.connected = False
self.server.close()
以下是发送SeekBar值的Android代码段:
public class MainActivity extends Activity implements OnSeekBarChangeListener{
SeekBar sbSpeed;
Socket socket;
BufferedReader reader;
PrintWriter writer;
Communication communication;
boolean connected = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
sbSpeed = (SeekBar) findViewById(R.id.sbSpeed);
sbSpeed.setOnSeekBarChangeListener(this);
communication = new Communication();
// the Thread is started when clicking on a button
}
class Communication implements Runnable{
public PrintWriter writer;
public BufferedReader reader;
public Socket socket;
public boolean ok;
public Communication(){
ok = true;
}
@Override
public void run() {
try{
socket = new Socket(InetAddress.getByName("192.168.42.1"), 8888);
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
writer = new PrintWriter(new OutputStreamWriter(socket.getOutputStream()));
while(ok){
String line = reader.readLine();
//parse the line...
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
@Override
public void onProgressChanged(SeekBar sb, int progress, boolean fromUser) {
String text = "SPEED::" + progress;
communication.writer.write(text);
communication.writer.flush();
tvSpeed.setText(progress + "");
}
有更好的沟通方式吗?在程序中应该更改什么以避免通信期间出现错误?
编辑:示例已添加。假设此方法位于Connection类中。
def example():
while True:
user_data = read()
if user_data[0] == "SPEED":
speed = int(user_data[1]) # HERE IS THE VALUEERROR THROWN