使用SocketServer 模块来完成服务端编程
1、服务端代码如下:
#!/usr/bin/python
#!coding:utf-8 import SocketServer as socketserver class ClientHandler(socketserver.BaseRequestHandler):
def handle(self):
print '[info] server has recive a connection :{0}'.format(self.client_address)
while True:
reciveData=self.request.recv(1024)
if not reciveData:print '[info] server the client has logout';break
print '[info] server has reviced this :{0}'.format(reciveData.decode())
reply='this is the reply information form server -->{0}'.format(reciveData.decode())
self.request.send(reply.encode())
if __name__=="__main__":
hostIp='127.0.0.1'
port=2048
server=socketserver.ThreadingTCPServer((hostIp,port),ClientHandler)
server.serve_forever()
2、客户端的代码如下:
#!/usr/bin/python
#!coding:utf-8 from socket import *
import os,sys if __name__ == "__main__":
#定义套接字
hostIp='127.0.0.1'
port=2048
sock=socket(AF_INET,SOCK_STREAM)
messages=['hello I am a client']
messages=messages+sys.argv[1:]
sock.connect((hostIp,port))
print '[info] 已经连接到server ' for message in messages:
sock.send(message.encode())
print sock.recv(1024).decode()
sock.close()