python tcp .demo
client:
# -*- coding: utf-8 -*- import socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) s.connect(('127.0.0.1',9999)) print(s.recv(1024)) for data in ['zhang','liu','wang']: s.send(data) print(s.recv(1024)) s.send('exit') s.close()
server:
# -*- coding: utf-8 -*- #引入模块 import socket import threading import time def tcplink(sock,addr): print('Accept new connection from {0}:{0}...'.format(addr)) sock.send('Welcome!') while True: data=sock.recv(1024) time.sleep(1) if data=='exit' or not data: break sock.send('Hello,%s!'%data) sock.close() print('Connection from {0}:{0} closed'.format(addr)) #创建socket s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) #监听端口 s.bind(('127.0.0.1',9999)) s.listen(5) print('Waiting for connection...') while True: #接受一个新连接 sock,addr=s.accept() #创建新线程来处理TCP连接 t=threading.Thread(target=tcplink(sock,addr))
参考:
https://www.cnblogs.com/suguangti/p/10814737.html
https://www.cnblogs.com/huihui0708/p/8594817.html