此文章引用于一位很厉害的师兄
服务器端代码:
# -*- 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()
1.首先开两个IDLE,分别打开服务器端和客户器端代码。
2.F5运行服务器端代码,会出现waiting client connection...
3.F5运行客户端代码,会出现input command: ;
4.这时服务器和客户端就连接上了,可以正常的通信啦,如图:
5.再次运行服务器端代码时会出现错误,这时可以通过任务管理器,将其中的pythonw.exe进程结束,重新打开,编译就可以啦!