python tcp发送接收数据

对于tcp server,一般流程为创建套接字,绑定,监听,accep链接(发生三次握手,阻塞),recv(阻塞),send

对于tcp client,一般流程为创建套接字,连接,发送,接收(阻塞)

需要注意的是发送和接收的都必须是bytes类型的数据,str转bytes使用encode,bytes转str使用decode

服务端例子:

from socket import *
from time import ctime

host = ''

port = 23333
buffsize = 1024
ADDR = (host,port)

tctime = socket(AF_INET,SOCK_STREAM)
tctime.bind(ADDR)
tctime.listen(3)

while True:
    print('Wait for connection ...')
    tctimeClient,addr = tctime.accept()
    print("Connection from :",addr)

    while True:
        data = tctimeClient.recv(buffsize)
        print(type(data))
        if not data:
            break
        tctimeClient.send(('[%s] %s' % (ctime(),data)).encode())
    tctimeClient.close()
tctimeClient.close()

客户端例子

from socket import *
from time import ctime
host = "localhost"
port = 23333
bufsize = 1024
addr = (host, port)
tcpClient = socket(AF_INET,SOCK_STREAM)
tcpClient.connect(addr)
while True:
    data = input(">")
    if not data:
        break
    sendData = bytes(data, encoding="utf8")
    tcpClient.send(sendData)
    data = tcpClient.recv(bufsize).decode()
    if not data:
        break
    print(data)
tcpClient.close()

猜你喜欢

转载自blog.csdn.net/mdjgold3/article/details/86530197
今日推荐