[python]代码库
#! /usr/bin/env python
#服务器(tsTserv.py)
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 'Waiting for connection...'
tcpCliSock,addr = tcpSerSock.accept()
print '...connection from:',addr
while True:
data = tcpCliSock.recv(BUFSIZ)
if not data:
break
tcpCliSock.send('[%s] %s' % (ctime(),data))
#tcpCliSock.close() 不关掉会报错
tcpSerSock.close()
=====================================================
#! /usr/bin/env python
#客户端(tsTclnt.py)
from socket import *
HOST = '192.168.1.190'
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()
==========================================================
服务器运行
[root@dogood core16]# python tsTserv.py
Waiting for connection...
...connection from: ('192.168.1.110', 1050)
Waiting for connection...
==========================================================
客户端运行
>>>
> How do you do?
[Thu Jan 31 06:46:27 2013] How do you do?
> 我很好
[Thu Jan 31 06:46:40 2013] 我很好
> ''
[Thu Jan 31 06:46:50 2013] ''
>
>>>