Python3编写TCP、UDP客户端和服务器

今日学习Python,学习书本叫《Python核心编程(第三版)》!

按照书本的代码编写,发现TCP和UDP的客户端都无法正确显示信息,根据错误提示,在网上搜集了原因,不敢独享,并在此备案

参考:https://stackoverflow.com/questions/13274553/python-3-3-socket-typeerror

原因是Python3.1之后的改动,

Python3 TCP时间戳服务器端代码

#!/usr/bin/env python

from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
    print('waiting for connecting...')
    tcpCliSock, addr = tcpSerSock.accept()
    print('...connect from:',addr)

    while True:
        data = tcpCliSock.recv(BUFSIZ)
        if not data:
            break
        response = '[%s] %s' % (ctime(), data.decode('utf-8'))
        tcpCliSock.send(response.encode('utf-8'))

    tcpCliSock.close()
tcpSerSock.close()

Python3 TCP时间戳服客户端代码

#!/usr/bin/env python

from socket import *

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = input('> ')
    if not data:
        break
    tcpCliSock.send(data.encode('utf-8'))
    data = tcpCliSock.recv(BUFSIZ)
    if not data:
        break
    print(data.decode('utf-8'))

tcpCliSock.close()

TCP服务器端运行图

TCP客户端运行图

 

Python3 UDP时间戳服务器端代码

#!/usr/bin/env python3

from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

udpSerSock = socket(AF_INET,SOCK_DGRAM)
udpSerSock.bind(ADDR)

while True:
    print('waiting for message ...')
    data,addr = udpSerSock.recvfrom(BUFSIZ)
    response = '[%s] %s' % (ctime(), data.decode('utf-8'))
    udpSerSock.sendto(response.encode('utf-8'),addr)
    print('..received from and returned to:')

udpSerSock.close()

Python3 UDP时间戳服客户端代码

#!/usr/bin/env python3

from socket import *

HOST = 'localhost'
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

udpCliSock = socket(AF_INET,SOCK_DGRAM)

while True:
    data = input('> ')
    if not data:
        break
    udpCliSock.sendto(data.encode('utf-8'),ADDR)
    data,ADDR = udpCliSock.recvfrom(BUFSIZ)
    if not data:
        break
    print(data.decode('utf-8'))

udpCliSock.close()

 

UDP服务器端运行图

UDP客户端运行图

 

 

 

 

 

转载于:https://my.oschina.net/doctorlzr1988/blog/1527640

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值