標籤:
目前處在學習python的階段,昨天看到了python的socket模組,分別實現TCP、UDP時間戳記回顯。
1、tcp通訊server和client代碼
# tcpServer.py#!/usr/bin/python# -*- coding: utf-8 -*-from socket import *from time import ctimeHOST = ‘‘PORT = 21156BUFSIZE = 1024ADDR = (HOST,PORT)tcpServerSock = socket(AF_INET,SOCK_STREAM)tcpServerSock.bind(ADDR)tcpServerSock.listen(5)while True:print ‘waiting for connection...‘tcpClientSock ,addr = tcpServerSock.accept()print ‘...connected from:‘,addrwhile True:data=tcpClientSock.recv(BUFSIZE)if not data:breaktcpClientSock.send(‘[%s] %s‘ % (ctime(),data)) tcpClientSock.close()tcpServerSock.close
# tcpClient.py#!/usr/bin/python# -*- coding: utf-8 -*-from socket import *HOST = ‘localhost‘PORT = 21156BUFSIZE = 1024ADDR = (HOST,PORT)tcpClientSock = socket(AF_INET,SOCK_STREAM)tcpClientSock.connect(ADDR)while True:data = raw_input(‘>‘)if not data:breaktcpClientSock.send(data)data = tcpClientSock.recv(BUFSIZE)if not data:breakprint datatcpClientSock.close()
2、udp通訊server和client代碼
#udpServer.py#!/usr/bin/python# -*- coding: utf-8 -*-from socket import *from time import ctimeHOST = ‘‘PORT = 21156BUFSIZE = 1024ADDR = (HOST,PORT)udpServerSock = socket(AF_INET,SOCK_DGRAM)udpServerSock.bind(ADDR)while True:print ‘waiting for message...‘data ,addr = udpServerSock.recvfrom(BUFSIZE)udpServerSock.sendto(‘[%s] %s‘ % (ctime(),data), addr)print ‘...received from and returned to:‘,addr tcpClientSock.close()tcpServerSock.close
#udpClient.py#!/usr/bin/python# -*- coding: utf-8 -*-from socket import *# from time import ctimeHOST = ‘localhost‘PORT = 21156BUFSIZE = 1024ADDR = (HOST,PORT)udpClientSock = socket(AF_INET,SOCK_DGRAM)while True:data = raw_input(‘>‘)if not data:breakudpClientSock.sendto(data,ADDR)data,ADDR = udpClientSock.recvfrom(BUFSIZE)if not data:breakprint dataudpClientSock.close()
Python的socket編程