python学习(1)--实现简单的服务器与客户端

来源:互联网 发布:网络对于大学生的影响 编辑:程序博客网 时间:2024/05/20 06:54

这几天开始学习python,发现python确实强大,主要是提供了功能强大的标准库。比如用socket模块写一个简单的服务器与客户端,只需要10来行代码。

服务器:

#!/usr/bin/pythonimport sockets = socket.socket()host = socket.gethostname()port = 1234s.bind((host, port))s.listen(5)while True:    c, addr = s.accept()    print ('Got connection from',addr)    c.send(b'Thank you for connecting')
    c.close()

网上的例子中,c.send()的参数为,'Thank you for connecting',结果报类型异常。原来python3.0开始,send的参数为字节型的,应写成

    c.send(b'Thank you for connecting')

客户端:

#!/usr/bin/pythonimport sockets = socket.socket()host = socket.gethostname()port = 1234s.connect((host, port))print(s.recv(1234))s.close()           

原创粉丝点击