要解决Android客户端套接字无法连接到Python服务器套接字的问题,需要确保以下几点:
确保Android设备和Python服务器在同一个局域网中,可以相互访问。
在Android客户端中正确设置服务器的IP地址和端口号。
下面是一个示例代码,展示了如何在Android客户端中使用套接字连接到Python服务器:
Android客户端代码:
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 {
private static final String SERVER_IP = "your_server_ip";
private static final int SERVER_PORT = 1234;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new Runnable() {
@Override
public void run() {
try {
// 创建套接字并连接到服务器
Socket socket = new Socket(SERVER_IP, SERVER_PORT);
// 通过套接字获取输入输出流
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
// 向服务器发送数据
out.println("Hello from Android client");
// 从服务器接收响应
String response = in.readLine();
Log.d("TCP", "Response from server: " + response);
// 关闭套接字和流
out.close();
in.close();
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
}
Python服务器代码:
import socket
SERVER_IP = 'your_server_ip'
SERVER_PORT = 1234
def main():
# 创建套接字并监听端口
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_socket.bind((SERVER_IP, SERVER_PORT))
server_socket.listen(1)
print('Server listening on {}:{}'.format(SERVER_IP, SERVER_PORT))
while True:
# 接受客户端连接
client_socket, client_address = server_socket.accept()
print('Client connected from {}:{}'.format(client_address[0], client_address[1]))
# 从客户端接收数据
data = client_socket.recv(1024).decode()
print('Received data from client:', data)
# 向客户端发送响应
response = 'Hello from Python server'
client_socket.sendall(response.encode())
# 关闭客户端套接字
client_socket.close()
if __name__ == '__main__':
main()
确保在AndroidManifest.xml文件中添加了与网络连接相关的权限:
将代码中的"your_server_ip"替换为Python服务器的IP地址。运行Android客户端应用程序,并确保Python服务器正在运行。如果一切正常,Android客户端将能够连接到Python服务器,并进行数据交换。