1、服务端 server.py
# -*- coding: utf-8 -*- import socket
import argparse host = 'localhost'
data_payload = 2048
backlog = 5 def echo_server(port):
# 建立一个TCP服务端
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# 设置套接字复用
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
# 绑定套接字到端口
server_address = (host, port)
print 'Starting up echo server on %s port %s' % server_address
sock.bind(server_address)
# 监听客户端,backlog值设定连接序列的最大编号
sock.listen(backlog)
while True:
print 'Waiting to receive message from client'
client, address = sock.accept()
data = client.recv(data_payload)
if data:
print 'Receive Data:%s' % data # 返回处理过的数据
data = '<worked>'+data+'</worked>'
client.send(data)
print 'Sent %s bytes back to %s' % (data, address)
# 断开连接
client.close() if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Socket Server Example')
parser.add_argument('--port', action='store', dest='port', type=int, required=True)
given_args = parser.parse_args()
port = given_args.port
echo_server(port)
2、客户端client.py
# -*- coding: utf-8 -*-
import socket
import argparse host = 'localhost' def echo_client(port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server_address = (host, port)
print 'Connecting to %s port %s' % server_address
sock.connect(server_address) try:
message = '我是一个程序猿'
# 将内容在CMD窗口内转换成GBK编码
message = message.decode('utf-8').encode('gbk')
print 'Sending: %s' % message
sock.sendall(message) amount_received = 0
amount_expected = len(message) while amount_received < amount_expected:
data = sock.recv(16)
amount_received += len(data)
print 'Received:%s' % data
except socket.error, e:
print 'Socket error: %s' % str(e)
except Exception, e:
print 'Other error: %s' % str(e)
finally:
print 'Closing connection to the server'
sock.close() if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Socket Server Example')
parser.add_argument('--port', action='store', dest='port', type=int, required=True)
given_args = parser.parse_args()
port = given_args.port
print port
echo_client(port)
3.运行
python server.py --port=9900
python client.py --port=9900