首页 > 编程语言 > 详细

python 网络编程第四版

时间:2016-01-03 11:06:29      阅读:154      评论:0      收藏:0      [点我收藏+]

使用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()
    

 

python 网络编程第四版

原文:http://www.cnblogs.com/JiangLe/p/5095831.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!