客户端 - 服务器消息传递给出错误(Python - 套接字编程)

时间:2016-11-30 20:59:05

标签: python sockets network-programming client-server

我正在尝试使用python(而不是python3)编写一个简单的客户端 - 服务器程序,每当我键入要发送的消息时,它会给我带来各种错误,例如:

文件"",第1行     你好,我的名字是darp            ^ SyntaxError:语法无效

OR

文件"",第1行,in NameError:name'你好'未定义

OR

文件"",第1行     你好,世界               ^ 语法错误:解析

时出现意外的EOF

这是服务器代码:

import socket

def Main():
    host = socket.gethostname()
    port = 5000

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

    s.listen(1)
    c, addr = s.accept()
    print("Connection from: "+str(addr))
    while True:
        data = c.recv(1024).decode('utf-8')
        if not data:
            break
        print("From connected user: "+data)
        data = data.upper()
        print("Sending: "+data)
        c.send(data.encode('utf-8'))
    c.close()

if __name__ == '__main__':
    Main()

这是客户端代码

import socket

def Main():
    host = socket.gethostname()
    port = 5000

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

    message = input("-> ")
    while message != 'q':
        s.send(message.encode('utf-8'))
        data = s.recv(1024).decode('utf-8')
        print("Recieved from server: " + data)
        message = input("-> ")
    s.close()

if __name__ == '__main__':
    Main()

即使我可以创建此连接,但在键入消息后会出现问题。任何帮助将不胜感激,谢谢!

3 个答案:

答案 0 :(得分:0)

在Python2中使用raw_input代替input

答案 1 :(得分:0)

您应该使用raw_input代替input,因为raw_input会捕获您的输入并将其转换为正确的类型。使用input时,您应该在输入周围添加引号。

您可以在python文档中查看:https://docs.python.org/2/library/functions.html#raw_input

答案 2 :(得分:0)

就代码而言,您需要在此处进行的唯一更改是服务器代码。用c.close()替换c.close(),因为c是一个连接变量,而s是根据你的代码服务器的套接字。

我已经使代码运行,在按预期运行更改后运行。我在Python 3中执行它。

服务器代码在这里:

import socket

def Main():
    host = "127.0.0.1"       # supply different hostname instead of socket.gethostname()
    port = 5000

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

    s.listen(1)
    c, addr = s.accept()
    print("Connection from: "+str(addr))
    while True:
        data = c.recv(1024).decode('utf-8')
        if not data:
            break
        print("From connected user: "+data)
        data = data.upper()
        print("Sending: "+data)
        c.send(data.encode('utf-8'))
    s.close()           # it is s which indicates socket

if __name__ == '__main__':
    Main()

客户端代码由您提供:

import socket

def Main():
# here, client is using the hostname whereas you need to give different 
# hostname for the server (127.0.0.1 for example) otherwise the code doesn't 
# work.You can do the reverse as well.
    host = socket.gethostname()
    port = 5000

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

    message = input("-> ")
    while message != 'q':
        s.send(message.encode('utf-8'))
        data = s.recv(1024).decode('utf-8')
        print("Recieved from server: " + data)
        message = input("-> ")
    s.close()

if __name__ == '__main__':
    Main()