【发布时间】:2020-09-17 19:15:54
【问题描述】:
我正在尝试将数据从 python 服务器发送到 android 客户端,但它不接受来自服务器的任何数据。但它显示它已与服务器连接。我无法识别任何错误。
这是我在 android java 中的客户端代码。
package com.example.socketinput;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
Thread Thread1 = null;
String SERVER_IP="192.168.1.6";
int SERVER_PORT=9857;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Thread1 = new Thread(new Thread1());
Thread1.start();
}
private PrintWriter output;
private BufferedReader input;
class Thread1 implements Runnable {
public void run() {
Socket socket;
try {
socket = new Socket(SERVER_IP, SERVER_PORT);
output = new PrintWriter(socket.getOutputStream());
input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("Server", "Connected");
}
});
new Thread(new Thread2()).start();
} catch (IOException e) {
Log.i("Server", "Error in thread 1");
}
}
}
class Thread2 implements Runnable {
@Override
public void run() {
while (true) {
try {
final String message = input.readLine();
if (message != null) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.i("Server", message);
}
});
} else {
Thread1 = new Thread(new Thread1());
Thread1.start();
return;
}
} catch (IOException e) {
Log.i("Server", "Error in thread 2");
e.printStackTrace();
}
}
}
}
}
这是我的 python 服务器代码。
#!/usr/bin/env python
# coding: utf-8
# In[1]:
import socket
# In[2]:
socket.gethostname()
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(('', 9857))
s.listen(5)
# In[ ]:
while True:
clientsocket, address = s.accept()
print(f"connection from {address} has been established!")
clientsocket.send(bytes("welcome to the server!","utf-8"))
while True:
msg=input()
clientsocket.send(bytes(msg,"utf-8"))
android 清单文件是-:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.socketinput">
<uses-permission android:name = "android.permission.INTERNET" />
<uses-permission android:name = "android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Note-Android 应用程序和 python 代码连接在同一台服务器上。
【问题讨论】:
-
您在服务器端和客户端都看到了哪些消息?请张贴截图或复制粘贴输出。
-
你不必使用runOnUiThread来调用Log.i。
-
现在检查我已经粘贴了输出的截图