python socket编程例子 « Rednat Linux网络日志平台_linux集群_gfs文件系统_iscsi存储配置_ldap服务加密_rac负载均衡_data guard异地备份_ogg流复制技术_rman备份恢复 
首页 » python编程 » python socket编程例子

python socket编程例子

时间:2013-10-28作者:felix.chan分类:python编程评论:0

清注意多进程和多线程的区别,以及该种方法应用在哪些不同的场景中比较合适。

官方demo,server端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
import socket
 
HOST = ''                 # Symbolic name meaning all available interfaces
PORT = 50007              # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
conn, addr = s.accept()
print 'Connected by', addr
while 1:
    data = conn.recv(1024)
    if not data: break
    conn.sendall(data)
conn.close()

官方demo,client端:

1
2
3
4
5
6
7
8
9
10
11
# Echo client program
import socket
 
HOST = 'daring.cwi.nl'    # The remote host
PORT = 50007              # The same port as used by the server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.sendall('Hello, world')
data = s.recv(1024)
s.close()
print 'Received', repr(data)

SocketServer单线程demo, server端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#!/usr/bin/env python
 
 
from SocketServer import (TCPServer as TCP,StreamRequestHandler as SRH)
from time import ctime
 
HOST = ''
PORT = 9999
ADDR = (HOST,PORT)
 
class MyRequestHandler(SRH):
    def handle(self):
        print '...connected from:',self.client_address
        self.wfile.write('[%s] %s ' % (ctime(),self.rfile.readline()))
 
tcpServ= TCP(ADDR,MyRequestHandler)
print 'waiting for connection...'
tcpServ.serve_forever()

SocketServer多线程demo, server端:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
#!/usr/bin/env python
import threading
import SocketServer
 
users = []
 
class MyTCPHandler(SocketServer.StreamRequestHandler):
    def handle(self):
        username = None
        while True:
            self.data = self.rfile.readline().strip()
            cur_thread = threading.currentThread()
            print "RECV from ", self.client_address[0]
            cmd = self.data
            if cmd == None or len(cmd) == 0:
                break;
            print cmd
            # business logic here
            try:
                if cmd.startswith('echo'):
                    result = cmd[5:]
                elif cmd.startswith('login'):
                    username = cmd[6:]
                    users.append({username:self.wfile})
                    result = username + ' logined.'
                elif cmd == 'quit':
                    break
                else:
                    result = 'error cmd'
                self.wfile.write(result)
                self.wfile.write('\n')
            except:
                print 'error'
                break
        try:
            if username != None:
                users.remove(username)
        except:
            pass
        print username, ' closed.'
 
class ThreadedTCPServer(SocketServer.ThreadingMixIn, SocketServer.TCPServer):
    allow_reuse_address=True
    pass
 
if __name__ == "__main__":
    HOST, PORT = "localhost", 9999
 
    server = ThreadedTCPServer((HOST, PORT), MyTCPHandler)
    server_thread = threading.Thread(target=server.serve_forever)
    server_thread.setDaemon(True)
    server_thread.start()
    server.serve_forever()

其中 allow_reuse_address=True 表示可以复用端口,类似开启了socket.SO_REUSEADDR选项,否则当server端进程意外终止时,如果在立刻启动改进程会提示:socket.error: [Errno 98] Address already in use ,这个是根据系统的time_wait时间来决定的,默认是120秒。linux系统通常为60秒,bsd系统为30秒。

原创文章,转载请注明: 转载自红防联盟www.rednat.com

本文链接地址: python socket编程例子

|2|right
0 条评论

暂时没有评论!

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>