套接字编程不起作用

时间:2016-10-10 21:20:12

标签: python sockets python-3.x

经过一些教程和一些文档阅读后,我尝试使用套接字创建一些简单的客户端 - 服务器应用程序。这是我已经完成的(使用Python 3.5):

服务器

import socket
import time

def Main():
    host = "127.0.0.1"
    port = 5001

    mySocket = socket.socket()
    mySocket.bind((host, port))

    mySocket.listen(1)
    conn, addr = mySocket.accept()
    print("Connection from: " + str(addr))
    while True:
        data = conn.recv(1024).decode()
        if not data:
            break
        print("from connected  user: " + str(data))

        data = str(data).upper()
        print("Recived from User: " + str(data))

        data = input(" s2 ")
        conn.send(data.encode())

    conn.close()


if __name__ == '__main__':
    Main()

客户端

import socket

def Main():
    host = '127.0.0.1'
    port = 5001

    mySocket = socket.socket()
    mySocket.connect((host, port))

    message = input(" c1 ")

    while message != 'q':
        mySocket.send(message.encode())
        data = mySocket.recv(1024).decode()

        print('Received from server: ' + data)

        message = input(" c2 ")

    mySocket.close()


if __name__ == '__main__':
    Main()

我无法弄清楚为什么if not data是真的。

0 个答案:

没有答案