python网络编程小例子
版本:python 2.7.3
开发工具:IDLE (Python GUI)和Eclipse Pydev
服务器端代码:
# -*- 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": breaksock.close()
实验过程:
在Eclipse编程环境下,上述代码运行没有任何的问题。但是在IDLE中,首次运行‘Run Model’时也能正常运行。运行结果如下:
[img1]
[img2]
但是,当服务器程序再次运行时,会出现如下错误:
[img3]
此时,是因为sock绑定失败,原因是因为第一次运行的窗口进程没有关闭!在任务管理器中,找到进程pythonw.exe关闭,然后再次运行正常!
注:IDLE代码整理的快捷键:和matlab很像,选中一段代码,Ctrl+[向左边缩进 Ctrl+] 向右边缩进。Python语法是强制缩进的
源代码下载地址:http://download.csdn.net/detail/nuptboyzhb/4929631
未经允许不得用于商业目的