skcket编程实例
socket编程服务端编码如下:
#!/usr/bin/env python from socket import * from time import ctime HOST='' PORT=21567 BUFSIZ = 1024 ADDR =(HOST,PORT) tcpSerSock = socket(AF_INET,SOCK_STREAM) tcpSerSock.bind(ADDR) tcpSerSock.listen(5) while True: print 'waitig for connection...' tcpCliSock,addr=tcpSerSock.accept() print '...connected from:',addr while True: data = tcpCliSock.recv(BUFSIZ) if not data: break tcpCliSock.send('[%s] %s' % (ctime(),data)) print [ctime()],':',data tcpCliSock.close() tcpSerSock.close()
socket客户端代码:
#!/usr/bin/env python from socket import * HOST='localhost' PORT=21567 BUFSIZ=1024 ADDR=(HOST,PORT) tcpCliSock=socket(AF_INET,SOCK_STREAM) print 1 tcpCliSock.connect(ADDR) print 2 while True: data=raw_input('>') if not data: break tcpCliSock.send(data) data=tcpCliSock.recv(BUFSIZ) if not data: break print data tcpCliSock.close()
服务端启动:
[nanjing3@master python]$ ./tsTserv.py waitig for connection...
客户端启动并输入信息:
[nanjing3@master python]$ ./tscli.py 1 2 >1 [Wed Nov 7 02:29:25 2012] 1 >2 [Wed Nov 7 02:29:34 2012] 2 >hi [Wed Nov 7 02:29:39 2012] hi >how are you! [Wed Nov 7 02:29:47 2012] how are you!
服务端接收到信息:
[nanjing3@master python]$ ./tsTserv.py waitig for connection... ...connected from: ('127.0.0.1', 51800) ['Wed Nov 7 02:29:25 2012'] : 1 ['Wed Nov 7 02:29:34 2012'] : 2 ['Wed Nov 7 02:29:39 2012'] : hi ['Wed Nov 7 02:29:47 2012'] : how are you!
端口占用情况:
[root@master ~]# netstat |grep 21567 tcp 0 0 localhost.localdomain:51800 localhost.localdomain:21567 ESTABLISHED tcp 0 0 localhost.localdomain:21567 localhost.localdomain:51800 ESTABLISHED