未显示期望的输出

问题描述 投票:0回答:1

你好,程序员。我遵循了本教程https://www.youtube.com/watch?v=QihjI84Z2tQ这些服务器和客户端已成功连接但是当我尝试构建时,它没有在客户端终端上显示所需的输出。服务器端终端没有任何反应。

这是我在服务器端的代码:

import socket
import numpy as np
import encodings

HOST = '192.168.0.177'  # Standard loopback interface address (localhost)
PORT = 65432        # Port to listen on (non-privileged ports are > 1023)


def random_data():          # ANY DATA YOU WANT TO SEND WRITE YOUR SENSOR CODE HERE

    x1 = np.random.randint(0, 55, None)         # Dummy temperature
    y1 = np.random.randint(0, 45, None)         # Dummy humidigy
    my_sensor = "{},{}".format(x1,y1)
    return my_sensor                            # return data seperated by comma


def my_server():

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        print("Server Started waiting for client to connect ")
        s.bind((HOST, PORT))
        s.listen(5)
        conn, addr = s.accept()

        with conn:
            print('Connected by', addr)
            while True:

                data = conn.recv(1024).decode('utf-8')

                if str(data) == "Data":

                    print("Ok Sending data ")

                    my_data = random_data()

                    x_encoded_data = my_data.encode('utf-8')

                    conn.sendall(x_encoded_data)

                elif  str(data) == "Quit":
                    print("shutting down server ")
                    break

                if not data:
                    break
                else:
                    pass


if __name__ == '__main__':
    while 1:
        my_server()

这是我的客户代码:

import socket
import threading
import time


HOST = '192.168.0.177'  # The server's hostname or IP address
PORT = 65432        # The port used by the server


def process_data_from_server(x):
    x1, y1 = x.split(",")
    return x1,y1


def my_client():
    threading.Timer(11, my_client).start()

    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
        s.connect((HOST, PORT))

        my = input("Data")

        my_inp = my.encode('utf-8')

        s.sendall(my_inp)

        data = s.recv(1024).decode('utf-8')

        x_temperature,y_humidity = process_data_from_server(data)

        print("Temperature {}".format(x_temperature))
        print("Humidity {}".format(y_humidity))

        s.close()
        time.sleep(5)


if __name__ == "__main__":
    while 1:
        my_client()

我已经尝试过通过直接将"Data"打印到终端上的许多解决方案。谁能帮我吗?

python sockets raspberry-pi port host
1个回答
0
投票

确定,我发现了问题。我在运行client.py脚本时使用Sublime Text 3,当我在构建中发布时,它什么也没有响应。所以我将我的IDE更改为PYCharm,然后它起作用了。我不知道为什么希望对其他有此问题的人有所帮助。非常感谢。

© www.soinside.com 2019 - 2024. All rights reserved.