gpt4 book ai didi

java - 无法连接到 python 服务器(android [java] 客户端)

转载 作者:行者123 更新时间:2023-12-01 18:07:51 25 4
gpt4 key购买 nike

我有一个简单的 python 套接字服务器和简单的 android [java] 套接字客户端。客户端无法成功连接我的服务器。

我的服务器运行良好(我尝试过使用 python 中的简单套接字客户端)。

服务器(Python):

import socket
def main():
listening_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server_address = (' ', LISTEN_PORT)
listening_sock.bind(server_address)
listening_sock.listen(1)

client_soc, client_address = listening_sock.accept()

client_msg = client_soc.recv(1024)
client_msg = client_msg.decode()

print(client_msg)

answer = "hello " + client_msg
client_soc.sendall(answer.encode())

client_soc.close()

listening_sock.close()
#print(str(get_distance_by_four_points("31.766977", "34.622898", "31.769887", "34.625430", "31.772632", "34.628273", "31.779327", "34.632951") / 1000) + " km")


if __name__ == "__main__":
main()

客户端(java):

package com.example.client;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class MainActivity extends AppCompatActivity {
EditText etToServer;
TextView tvFromSer;

private static Socket sock;
private static ServerSocket serSock;
private static PrintWriter prWriter;
private static InputStreamReader in;
private static BufferedReader bf;

String message = "";
private static String LOCAL_IP = "127.0.0.1";
private static int PORT = 2002;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
etToServer = (EditText)findViewById(R.id.etxtUsername);
tvFromSer = (TextView)findViewById(R.id.tvFromServer);
}


public void sendMsg(View view) {
message = etToServer.getText().toString();

myTask myT = new myTask();
myT.execute();
}


class myTask extends AsyncTask<Void,Void, Void> {

@SuppressLint("WrongThread")
@Override
protected Void doInBackground(Void... voids) {
try {
sock = new Socket(LOCAL_IP, PORT);

prWriter = new PrintWriter(sock.getOutputStream());

prWriter.write(message);
prWriter.flush();
prWriter.close();

sock.close();
} catch (IOException e) {
e.printStackTrace();
tvFromSer.setText(e.toString());
}
return null;
}
}
}

java.net.connectException: failed to connect to /127.0.0.1 (port 2002) from /:: (port 58590): connect failed: ECONNREFUSED (Connection refused)

enter image description here

最佳答案

我认为您忘记在 AndroidManifest.xml 中授予权限

关于java - 无法连接到 python 服务器(android [java] 客户端),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60528262/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com