python-网络
1、tcp-ipv4方式
- python2
1)server端:
from socket import * from time import ctime HOST='' PORT=21567 BUFSIZ=1024 ADDR=(HOST,PORT) tcpsocket=socket(AF_INET,SOCK_STREAM) tcpsocket.bind(ADDR) tcpsocket.listen(5) while True: print("waiting for connecting...") tcpCliSock,addr=tcpsocket.accept() print('...connect from:',addr) while True: data=tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send('[%s] %s' % (ctime(),data)) tcpCliSock.close() tcpsocket.close()
2)client端
from socket import * HOST='127.0.0.1' PORT=21567 BUFSIZ=1024 ADDR=(HOST,PORT) tcpCliSock=socket(AF_INET,SOCK_STREAM) tcpCliSock.connect(ADDR) while True: data=raw_input('> ') if not data: break tcpCliSock.send(data) data=tcpCliSock.recv(BUFSIZ) if not data: break print(data) tcpCliSock.close()
- python3
1)server端:
from socket import * from time import ctime HOST='' PORT=21567 BUFSIZ=1024 ADDR=(HOST,PORT) tcpsocket=socket(AF_INET,SOCK_STREAM) tcpsocket.bind(ADDR) tcpsocket.listen(5) while True: print("waiting for connecting...") tcpCliSock,addr=tcpsocket.accept() print('...connect from:',addr) while True: data=tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send(('[%s] %s' % (ctime(),str(data,'utf-8'))).encode()) tcpCliSock.close() tcpsocket.close()
2)client端
from socket import * HOST='127.0.0.1' 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()) data=tcpCliSock.recv(BUFSIZ) if not data: break print(data.decode('utf-8')) tcpCliSock.close()
2、tcp-ipv6方式
与ipv4的区别:server和client中将AF_INET改为AF_INET6,client中将127.0.0.1改为::1,也可以用localhost(v4/v6都可以)。
3、udp-ipv4方式