服务器端代码:
# -*- coding: cp936 -*-
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)#初始化socket
sock.bind(("127.0.0.1", 8001))#绑定本机地址,8001端口
sock.listen(5)#等待客户连接
while True:
print "waiting client connection..."
connection,address = sock.accept()#接收客户连接请求
print "a client have connected..."
while True:
try:
connection.settimeout(5) #设置超时时间
buf = connection.recv(1024) #接收数据
if buf == "1":
connection.send("you have send me 1!welcome to server!")
elif buf=="2":
connection.send("you have send me 2!I have recv!")
elif buf=="3":
connection.send("close the connection!")
break
else:
connection.send("unknow command!")
except socket.timeout:
print "time out"
connection.close()
print "a client exit..."
客户端代码:
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 8001))
import time
time.sleep(2)
while True:
data=raw_input("input command:");
sock.send(data)
print sock.recv(1024)
if data=="3":
break
sock.close()