我想编写一个简单的android应用程序,将文本发送到python服务器,然后输入它的答案(在我们的例子中:数据中有多少元音),并使用Logcat查看它是否真正获得了数据。 除了客户端等待服务器响应的部分之外,所有的工作都很正常。 它只是被卡在那里,即使服务器说它发送数据回客户端。你知道吗
有人知道是什么导致了这个问题吗?你知道吗
更新:
在用Wireshark嗅探之后,我看到客户端和服务器发送给对方的数据是“格式错误的数据包”。有人知道为什么吗?你知道吗
我的客户代码:
public class MainActivity extends Activity {
private Socket socket;
private static final int SERVERPORT = 5000;
private static final String SERVER_IP = "10.0.0.1";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
try {
EditText et = (EditText) findViewById(R.id.EditText01);
String str = et.getText().toString();
PrintWriter out = new PrintWriter(new BufferedWriter(
new OutputStreamWriter(socket.getOutputStream())),
true);
out.println(str);
Log.i("Tag","sent " + str);
BufferedReader input = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
try {
String read = input.readLine();
Log.i("Tag","got " + read);
} catch (IOException e) {
e.printStackTrace();
}
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
class ClientThread implements Runnable {
@Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
我的服务器代码:
import socket
srv_sock = socket.socket()
ip = "0.0.0.0" # means local
port = 3001 # 0 means get random free port
srv_sock.bind((ip, port))
srv_sock.listen(5)
while True:
(new_sock, address) = srv_sock.accept()
print "Hello! this is a vowels server! You need to send a word or a
sentence and I'll give you the number of vowels in it!"
while True:
data = new_sock.recv(1024)
if data == "" :
print "Client Disconnected"
break
print "Received<<< " + data
data = data.upper()
to_send = "Num of vowels is "
cnt=0
if data.isdigit():
to_send = "ERROR:Number doesn't have any vowels!"
else:
for letter in data:
if (letter == 'A' or letter == 'E' or letter == 'O' or letter
== 'U' or letter == 'I'):
cnt += 1
to_send += str(cnt)
new_sock.send(unicode(to_send + "\n"))
print "Sent >>>" + to_send
new_sock.close()
srv_sock.close()
目前没有回答
相关问题 更多 >
编程相关推荐