展开全部
我从网上给你拷两个例子
服务器#!e68a84e8a2ad62616964757a686964616f31333332626635/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
data = sock.recv(32)
sys.stdout.write(data)
received += len(data)
sock.close()