code:python:simplesocketcode
Differences
This shows you the differences between two versions of the page.
Next revision | Previous revision | ||
code:python:simplesocketcode [2010/04/03 20:55] – created percy | code:python:simplesocketcode [2016/05/05 13:07] (current) – external edit 127.0.0.1 | ||
---|---|---|---|
Line 1: | Line 1: | ||
+ | ====== 简单的socket代码(包含server, | ||
+ | python socket最简单的代码,包含server, | ||
+ | |||
+ | ====== server.py ====== | ||
+ | pjq@gentoo-pjq ~/ | ||
+ | <file python server.py> | ||
+ | |||
+ | # | ||
+ | |||
+ | import socket | ||
+ | |||
+ | sock=socket.socket(socket.AF_INET, | ||
+ | |||
+ | sock.bind((' | ||
+ | |||
+ | sock.listen(5) | ||
+ | |||
+ | while True: | ||
+ | print ' | ||
+ | connection, | ||
+ | try: | ||
+ | connection.settimeout(5) | ||
+ | buf=connection.recv(1024) | ||
+ | if buf ==' | ||
+ | print ' | ||
+ | connection.send(' | ||
+ | else: | ||
+ | print ' | ||
+ | connection.send(' | ||
+ | except socket.timeout: | ||
+ | print 'time out' | ||
+ | print ' | ||
+ | connection.close() | ||
+ | </ | ||
+ | |||
+ | ====== client.py ====== | ||
+ | pjq@gentoo-pjq ~/ | ||
+ | <file python client.py> | ||
+ | # | ||
+ | |||
+ | import socket | ||
+ | import time | ||
+ | |||
+ | print ' | ||
+ | sock=socket.socket(socket.AF_INET, | ||
+ | |||
+ | |||
+ | print ' | ||
+ | sock.connect((' | ||
+ | time.sleep(2) | ||
+ | |||
+ | print ' | ||
+ | sock.send(' | ||
+ | |||
+ | print ' | ||
+ | print sock.recv(1024) | ||
+ | |||
+ | print 'Close socket' | ||
+ | sock.close() | ||
+ | |||
+ | </ | ||
+ | |||
+ | |||