socket代码(简单)
1 SERVER: 2 3 #!/usr/bin/python 4 # -*- coding: utf-8 -*- 5 import socket 6 import time 7 s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 s.bind(('', 12345)) 9 s.listen(5) 10 try: 11 12 while 1: 13 14 15 16 cs, ca = s.accept() 17 18 print cs, ca 19 while 1: 20 data = cs.recv(1024) 21 if not data: 22 raise Exception('recv nothing') 23 print data 24 cs.send(str(time.ctime())) 25 except Exception as e: 26 print e 27 s.close() 28 29 CLIENT: 30 31 import socket 32 33 host = '127.0.0.1' 34 port = 12345 35 bufsiz = 1024 36 ADDR = (host,port) 37 38 tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 39 tcpCliSock.connect(ADDR) 40 41 while True: 42 data = raw_input('> ') 43 if not data: 44 break 45 tcpCliSock.send(data) 46 data = tcpCliSock.recv(bufsiz) 47 if not data: 48 break 49 print data 50 51 52 53 tcpCliSock.close()