Python socket module implements TCP server-side client

Source: Internet
Author: User

Python socket module implements TCP server-side client
写了详细的注释,如果有哪一行不明白,可留言哦。
Server-side scripting
# _*_ coding: utf-8 _*___author__ = ‘xiaoke‘__date__ = ‘2018/6/13 14:39‘# 这个脚本创建一个TCP服务器,它接收来自客户端的消息,然后将消息加上时间戳前缀并返回客户端import socketfrom time import ctimeHOST = ‘‘PORT = 21567BUFSIZ = 4096ADDR = (HOST, PORT)# 创建TCP套接字tcpSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 创建UDP套接字# udpSock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)tcpSock.bind(ADDR)  # 将地址绑定到套接字上tcpSock.listen(5)  # 设置并启动TCP监听器while True:    print("waiting for connection....")    tcpCliSock, addr = tcpSock.accept()  # 被动接收TCP客户端连接,一直等待直到连接到达(阻塞)    print("... connected from", addr)    while True:        data = tcpCliSock.recv(BUFSIZ)  # 接收TCP消息        # print(data)        # 如果有数据加上时间戳后返回给客户端,因为只接受字节数据,所以把数据使用bytes函数转换        if not data:            break        tcpCliSock.send(bytes(‘[%s] %s‘ % (ctime(), data.decode(‘utf-8‘)), ‘utf-8‘))    tcpCliSock.close()# tcpSock.close()
Client Script
# _*_ coding: utf-8 _*___author__ = ‘xiaoke‘__date__ = ‘2018/6/13 16:01‘import socketimport sysHOST = ‘127.0.0.1‘PORT = 21567BUFSIZ = 4096ADDR = (HOST, PORT)# 创建客户端TCP连接tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)# 连接服务器try:    tcpCliSock.connect(ADDR)except Exception as e:    print("连接服务器失败:",e)    sys.exit(-1)while True:    data = input(‘> ‘)    if not data:        break    # 循环发送数据,直到没有数据发送退出    tcpCliSock.send(bytes(data, encoding=‘utf-8‘))    # 接收服务端返回的消息,如果没有消息返回,也将退出循环    data = tcpCliSock.recv(BUFSIZ)    if not data:        break    print(data.decode(‘utf-8‘))tcpCliSock.close()

Python socket module implements TCP server-side client

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.