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":
       break
sock.close()


 

实验过程:
在Eclipse编程环境下,上述代码运行没有任何的问题。但是在IDLE中,首次运行‘Run Model’时也能正常运行。运行结果如下:
[img1]

[img2]


但是,当服务器程序再次运行时,会出现如下错误:
[img3]

此时,是因为sock绑定失败,原因是因为第一次运行的窗口进程没有关闭!在任务管理器中,找到进程pythonw.exe关闭,然后再次运行正常!

注:IDLE代码整理的快捷键:和matlab很像,选中一段代码,Ctrl+[ 向左边缩进 Ctrl+] 向右边缩进。Python语法是强制缩进的
源代码下载地址:
http://download.csdn.net/detail/nuptboyzhb/4929631

未经允许不得用于商业目的

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值