python 8.2

TCP 通话实现:
服务器端

import socket
import threading
import time
'''
服务器端
'''
flag = 1
def TcpLink(sock, addr):
    print('接收到一个来自%s:%s的连接' % addr)
    sock.send(b'Welcome come on!')
    while True:
        data = sock.recv(1024)
        time.sleep(1)
        print('接收到的数据为:'+ data.decode('utf-8'))
        if (not data) or (data.decode('utf-8') == 'exit'):
            break
        
        sock.send(b'Hello!')    
    print('来自%s:%s的连接关闭了' % addr)
    sock.send(b'Ok')
    sock.close()

if __name__ == '__main__':
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(('127.0.0.1', 8080))
    s.listen(5)
    print('等待客户端连接...')
    while True:
        sock, addr = s.accept()
        t = threading.Thread(target = TcpLink, args = (sock, addr))
        t.start()

客户端

import socket
import threading
import time

if __name__ == '__main__':
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.connect(('127.0.0.1', 8080))
    time.sleep(5)
    print('接收到的数据:'+s.recv(1024).decode('utf-8'))
    t1 = time.time()
    while(time.time() - t1 <= 5.0):
        s.send(b'Roger!')
        print('接收到的数据:'+s.recv(1024).decode('utf-8'))
    s.send(b'exit')
    if(s.recv(1024).decode('utf-8') == 'Ok'):
        print('Closed now!')
        s.close()   

posted @ 2023-08-02 22:48  N0zoM1z0  阅读(11)  评论(0编辑  收藏  举报