python socket 编程的简单example

来源:互联网 发布:图片大小变小软件 编辑:程序博客网 时间:2024/06/04 18:18

  python 的确很强大,学习中ing....       一个简单的 socket 的例子。  

#!/usr/bin/python

from socket import *
def conto(ser,port) :
        try :
            sock = socket(AF_INET,SOCK_STREAM)
            sock.connect((ser,port))
       except:
            print "can't connect to : ",(ser,port)
            return 
        while True :
                inp = raw_input("Input Your words:")
                sock.send(inp)
                if inp == "exit" or inp == "quit" :
                        sock.close()
                        break


if __name__ == '__main__' :
        conto('localhost',8080)

   下面是server 的 code 的

#!/usr/bin/python

from socket import *

def start(host,port) :
        sock = socket(AF_INET,SOCK_STREAM)
        sock.bind((host,port))
        sock.listen(5)
        print 'Start To listen : '
        num=0
        while True:
                conn,addr=sock.accept()
                print 'New connection come : ' , addr
                num = num + 1
                while True:
                        data = conn.recv(1024)
                        if not data : break
                        print('Echo=>'+data)
                conn.close()
                if num >= 2 : break
        sock.close()


if __name__ == '__main__' :
        start('',8080)

原创粉丝点击