我从网上给你拷两个例子
服务器
#!/usr/bin/python
"USAGE: echoserver.py"
from SocketServer import BaseRequestHandler, TCPServer
import sys, socket
class EchoHandler(BaseRequestHandler):
def handle(self):
print "Client connected:", self.client_address
self.request.sendall(self.request.recv(2**16))
self.request.close()
if len(sys.argv) != 2:
print __doc__
else:
TCPServer(('', int(sys.argv[1])), EchoHandler).serve_forever()
客户端
#!/usr/bin/python
"USAGE: echoclient.py"
from socket import *
import sys
if len(sys.argv) != 4:
print __doc__
sys.exit(0)
sock = socket(AF_INET, SOCK_STREAM)
sock.connect((sys.argv[1], int(sys.argv[3])))
message = sys.argv[2]
messlen, received = sock.send(message), 0
if messlen != len(message):
print "Failed to send complete message"
print "Received: ",
while received < messlen:
data = sock.recv(32)
sys.stdout.write(data)
received += len(data)
sock.close()
可以用python支持的zeromq库,对socket抽象比较好,用起来简单
python 自带socket模块,只要去官网下个python就行了。简单的socket例子网上大把,这里就不详说了。
python自带了socket模块,不需要下载其他软件