服务端的代码,记得要先运行服务端,否则老是报error 100053:
代码如下:
import socket
import time
HOST = ''
PORT = 13651
BUFSIZE = 1024
ADDR =(HOST,PORT)
tcpSerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(10)#表示最多 能连接多少个
while True:
print 'wating for connection ...'
tcpCliSock , addr = tcpSerSock.accept()
print 'connecting from : %s' % str(addr)
while True:
data = tcpCliSock.recv(BUFSIZE)
if not data:
break
tcpCliSock.send('[%s] %s' % (time.ctime(),data))
tcpCliSock.close()#这个地方注意一下,是循环结束后再关掉
print 'tcpCliSock.close()'
tcpSerSock.close()
客服端代码:
import socket
HOST ='localhost'
PORT = 13651
BUFSIZE = 1024
ADDR =(HOST,PORT)
try:
tcpClientSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpClientSock.connect(ADDR)
except Exception as e:
print e
while True:
data = raw_input('please input the meassage send to server:')
if not data:
break
print data
try:
tcpClientSock.send(data)
data = tcpClientSock.recv(BUFSIZE)
except Exception as e:
print e
if not data:
break
print data
tcpClientSock.close()
运行的结果:
客户端的:
服务器端输出结果: