Java 和 Python 套接字可以在本地主机上工作,但不能在任何其他 IP 上工作

标签 java python-3.x raspberry-pi raspberry-pi3

这是Java中的客户端代码

public static void main(String[] args) {

        Socket rpiSocket = null; 
        DataInputStream in = null;
        PrintStream out = null;
        String str="Akif";

        try {
            rpiSocket = new Socket("localhost",5560); 
            out = new PrintStream(rpiSocket.getOutputStream());
            in = new DataInputStream(new BufferedInputStream(rpiSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: hostname");
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: hostname");
        }

        try {
        if (rpiSocket != null && out != null && in != null) {
            while(true) {
                System.out.println("Please input your command ");
                Scanner scanner = new Scanner(System.in);
                String command = scanner.nextLine();

                if(command.equals("KILL")) {
                    break;
                }

                System.out.println("Sending command to client: " + command);
                out.print(command);

                 byte[] bytes = new byte[1024];

                in.read(bytes);
                String reply = new String(bytes, "UTF-8");
                System.out.println("Reply from server: " + reply.trim());
            }
        }

            rpiSocket.close();
            System.out.println("Connections closed successfully");
        }
        catch (IOException e) {
            System.err.println("IOException:  " + e);
        }
    }

这是Python中的服务器代码

import socket
from sys import getsizeof

host = ''
#host = '192.168.2.181'
port = 5560

storedValue = "Yo, what's up?"

def setupServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created.")
    try:
        s.bind((host, port))
    except socket.error as msg:
        print(msg)
    print("Socket bind comPlete.")
    return s

def setupConnection():
    s.listen(1) # Allows one connection at a time.
    print("Waiting for client")
    conn, address = s.accept()
    return conn

def GET():
    reply = storedValue
    return reply

def REPEAT(dataMessage):
    reply = dataMessage[1]
    return reply

def dataTransfer(conn, s):
    # A big loop that sends/receives data until told not to.
    while True:
        # Receive the data
        data = conn.recv(1028) # receive the data
        data = data.decode('utf-8')
        data = data.strip()
        print("data value from client: " + data)
        # Split the data such that you separate the command
        # from the rest of the data.
        command = str(data)
        print("data length from client: " + command)
        reply = ""
        if command == "GET":
            reply = GET()
            print (command)
            print (reply)
        elif command == 'REPEAT':
            reply = REPEAT('akif')
        elif command == 'EXIT':
            print("Our client has left us :(")
            break
        elif command == 'KILL':
            print("Our server is shutting down.")
            s.close()
            break
        else:
            reply = 'Unknown Command'
        # Send the reply back to the client
        conn.sendall(bytes(reply, 'utf-8'))
        print("Data has been sent!")
    conn.close()

s = setupServer()

while True:
    try:
        conn = setupConnection()
        dataTransfer(conn, s)
    except:
        break

服务器和客户端在我的计算机(win 10 pro)上的本地主机上完美工作。但是,如果我在 Win 10 PC 上运行客户端并在 Rpi PC 上运行服务器,服务器工作正常,但客户端工作直到这一行“in.read(bytes);”它留在这里。

P.S. = I tried turn of Windows firewall and Windows Defender. I used wifi connection and I tried turned of modem firewall

我该怎么做才能解决这个问题。谢谢。

最佳答案

我解决了这个问题。问题是我使用的Python版本。问题发生在 pyton2 版本上,但在 python3 版本上它可以正常工作。

关于Java 和 Python 套接字可以在本地主机上工作,但不能在任何其他 IP 上工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49694538/

相关文章:

java - ScheduledExecutorService 多线程并行

Python - 使用字典检查查询并检索答案

python-3.x - 传递 None 时如何将默认值应用于 python 数据类字段?

Python GPSD 库导入配置

java - Ehcache Java Spring MVC 和分页 @Cacheable

java - 使用 sshpass ssh 到远程主机并使用 java 获取结果

Java - 创建一个 BufferedImage 克隆,它不引用原始图像

python-3.x - 将 anaconda 中所有当前安装的包保存到一个文件中

c++ - 如何在 Raspberry Pi 上使用 C++ 将接收到的 UDP 音频数据正确写入 ALSA

docker - 在 Intel 机器 (Mac) 上构建 ARM 架构的 Docker 镜像