Python核心程式設計——Chapter16

中大黑熊發表於2014-06-05

好吧,在拜讀完《Python網路程式設計基礎》之後,回頭再搞一搞16章的網路程式設計吧。

Let‘s go!

16.4.修改書上示例的TCP和UDP客戶端,使得伺服器的名字不要在程式碼裡寫死,要允許使用者指定一個主機名和埠。只有兩個值都沒有輸入是才使用預設值。

難度不大。

#tsTclnt.py
#!/usr/bin/env python
#-*-coding:utf-8-*-

from socket import *
import sys

if(len(sys.argv) < 3):
    HOST = 'localhost'
    PORT = 21567
else:
    HOST = sys.argv[1]
    PORT = int(sys.argv[2])

BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = raw_input('> ')
    if not data:
        break
    tcpCliSock.send(data)
    data = tcpCliSock.recv(BUFSIZ)
    if not data:
        break
    print data

tcpCliSock.close()

 

#tsUclnt.py
#!/usr/bin/env python
#-*- coding:utf-8 -*-

from socket import *
import sys

if(len(sys.argv) < 3):
    HOST = 'localhost'
    PORT = 21567
else:
    HOST = sys.argv[1]
    PORT = sys.argv[2]
    #print sys.argv[1],sys.argv[2]

BUFSIZ = 1024
ADDR = (HOST,int(PORT))

udpCliSock = socket(AF_INET,SOCK_DGRAM)

while True:
    data = raw_input('> ')
    if not data:
        break
    udpCliSock.sendto(data,ADDR)
    data,ADDR = udpCliSock.recvfrom(BUFSIZ)
    if not data:
        break
    print data

udpCliSock.close()

 

16.5.修改伺服器示例程式碼,使得它能根據不同的請求而作出應答。

這道題目本質上也不難,只需要在伺服器的死迴圈程式加上條件判斷即可。

版本1:純TCP伺服器端修改。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from socket import *
import time,os

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
    print 'waiting for connection...'
    tcpCliSock,addr = tcpSerSock.accept()
    print '...connected from:',addr

    while True:
        data = tcpCliSock.recv(BUFSIZ)
        data = data.strip()
        if not data:
            break
        if data == "date":
            tcpCliSock.send('%s' % (time.ctime(time.time())))
        elif data == "os":
            tcpCliSock.send('%s' % (os.name))
        elif data == "ls":
            tcpCliSock.send('%s' % (os.listdir(os.curdir)))
        else:
            tcpCliSock.send('[%s] %s' % (ctime(),data))
    tcpCliSock.close()

tcpSerSock.close()

版本2:使用現成的伺服器框架進行修改。

#!/usr/bin/env python
#-*-coding:utf-8-*-

from SocketServer import ThreadingMixIn,TCPServer,StreamRequestHandler
import time,os,re

class TxRequestHandler(StreamRequestHandler):
    def handle(self):
        req = self.rfile.readline().strip()
        m = re.match('(\w+)\s+([\w+/]+)',req)
        if req == "date":
            result = time.ctime(time.time())
        elif req == "os":
            result = os.name
        elif req == "ls":
            result = str(os.listdir(os.curdir))
        elif m is not None and m.lastindex == 2 and m.group(1) == 'ls':
            result = str(os.listdir(m.group(2)))
        else:
            result = """
date -- 伺服器將返回它的當前時間
os   -- 得到作業系統的資訊
ls   -- 得到當前目錄的檔案列表
"""
        self.wfile.write(result+"\n")

class TxServer(ThreadingMixIn,TCPServer):
    allow_reuse_address = 1

serveraddr = ('',8765)
srvr = TxServer(serveraddr,TxRequestHandler)
srvr.serve_forever()

 

16.7.實現一個半雙工的聊天方式,其中一個人是服務端,另一個人是客戶端。

其實也不難,只是將回射伺服器做部分修改就可以。

伺服器端:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from socket import *
from time import ctime

HOST = ''
PORT = 21567
BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpSerSock = socket(AF_INET,SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(5)

while True:
    print 'waiting for connection...'
    tcpCliSock,addr = tcpSerSock.accept()
    print '...connected from:',addr

    while True:
        rdata = tcpCliSock.recv(BUFSIZ)
        if not rdata:
            break
        print rdata
        sdata = raw_input(">")
        tcpCliSock.send('[%s] %s' % (ctime(),sdata))
    tcpCliSock.close()

tcpSerSock.close()

客戶端:

#!/usr/bin/env python
#-*-coding:utf-8-*-

from socket import *
import sys

if(len(sys.argv) < 3):
    HOST = 'localhost'
    PORT = 21567
else:
    HOST = sys.argv[1]
    PORT = int(sys.argv[2])

BUFSIZ = 1024
ADDR = (HOST,PORT)

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

while True:
    data = raw_input('> ')
    if not data:
        break
    tcpCliSock.send(data)
    data = tcpCliSock.recv(BUFSIZ)
    if not data:
        break
    print data

tcpCliSock.close()

 

16.8.實現一個全雙工的聊天方式,即兩個人可以獨立地傳送和接收訊息。

全雙工其實原理也不太難,但是我一直傻逼了,一直用寫伺服器端的方法去實現客戶端的程式。

我所使用的方法也是最常用的技術——多執行緒。以下是伺服器端和客戶端的編寫思路:

伺服器端:在伺服器端我主要用了一個主執行緒來accept客戶端的連結,沒接受了一個連線,就新建兩個執行緒,一個用於傳送訊息,一個用於接收訊息。

客戶端:思路完全不一樣,由於客戶端面對的只有伺服器,所以主執行緒只能是接收訊息(傳送訊息),然後傳送訊息(接收訊息)作為一個執行緒來併發。

由於這裡的資料並不是共享的,所以這裡的執行緒寫起來就很輕鬆,不用考慮同步問題。

伺服器端:

 

#!/usr/bin/env python
#-*- coding:utf-8 -*-
import socket,traceback,os
from threading import *

host = ''
port = 51423     #監聽所有的介面

#接受訊息的執行緒
def handlerecv(clientsock):
    print "New child",currentThread().getName()
    print "Got connection from",clientsock.getpeername()
    while True:
        data = clientsock.recv(4096)
        if not len(data):
            break
        print data
    clientsock.close()

#傳送訊息的執行緒
def handlesend(clientsock):
    while True:
        data = raw_input(">")
        data = data + "\n";   #加上換行,好看一點。
        clientsock.sendall(data)
    #關閉連線
    clientsock.close()

#建立套接字
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
s.bind((host,port))
s.listen(1)

while True:
    try:
        clientsock,clientaddr = s.accept()
    except KeyboardInterrupt:
        raise
    except:
        traceback.print_exc()
        continue

    t = Thread(target = handlerecv,args=[clientsock])
    t.setDaemon(1)
    t.start()

    r = Thread(target = handlesend,args=[clientsock])
    r.setDaemon(1)
    r.start()

 

客戶端:

#!/usr/bin/env python
#-*-coding:utf-8-*-

from socket import *
import sys
from threading import *

if(len(sys.argv) < 3):
    HOST = 'localhost'
    PORT = 51423
else:
    HOST = sys.argv[1]
    PORT = int(sys.argv[2])

BUFSIZ = 1024
ADDR = (HOST,PORT)
    
def handlesend(tcpCliSock):
    while True:
        sdata = raw_input('> ')
        if not sdata:
            break
        tcpCliSock.send(sdata)

    tcpCliSock.close()

tcpCliSock = socket(AF_INET,SOCK_STREAM)
tcpCliSock.connect(ADDR)

#建立傳送訊息的執行緒
s = Thread(target = handlesend,args=[tcpCliSock])
s.setDaemon(1)
s.start()

while True:
    rdata = tcpCliSock.recv(BUFSIZ)
    if not rdata:
        break
    print rdata
tcpCliSock.close()

 

16.10.實現一個多房間全雙工的聊天方式,把聊天伺服器改成支援多使用者版本。

其實思路差不多,只不過過程有點繁瑣,在伺服器端要建立字典,作為房間,然後每個套接字存在字典當中,然後作適當的分發。

另外一種方法使用廣播不知道可不可以了。

這裡直接貼人家寫的程式碼學習一下:

伺服器端:

 

#!/usr/bin/env python
# _*_ coding: utf8 _*_

from socket import *
from time import ctime
import threading
from string import split

HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST, PORT)

def Deal(sck, username, room):
    while True:
        data = sck.recv(BUFSIZE)
        for i in  clients[room].iterkeys():
            if i <> username:
                if data <> "quit":
                    clients[room][i].send("[%s] %s: %s" %(ctime(), username, data))
                else:
                    clients[room][i].send("使用者%s在%s退出房間%s" %(username, ctime(), room ))
        if data == "quit":
            del clients[room][username]    
            sck.send(data)
            sck.close()
            break
            

chatSerSock = socket(AF_INET, SOCK_STREAM)
chatSerSock.bind(ADDR)
chatSerSock.listen(5)

clients = {"":{},}

while True:
    print 'waiting for connection...'
    chatCliSock, addr = chatSerSock.accept()
    print "...connected romt: ", addr
    data = chatCliSock.recv(BUFSIZE)
    username, room = split(data)
    print username
    if not clients.has_key(room):
        clients[room] = {}
    if clients[room].has_key(username):
        chatCliSock.send("reuse")
        chatCliSock.close()
    else:
        chatCliSock.send("success")
        clients[room][username] = chatCliSock
        t = threading.Thread(target=Deal, args=(chatCliSock, username, room))
        t.start()

chatSerSock.close()

 

客戶端:

#!/usr/bin/env python
# _*_ coding: utf8 _*_

from socket import *
from time import ctime
import threading
import random
from sys import argv, exit, stdout
from getopt import gnu_getopt, GetoptError




help_info = ["cs.py [ -h | --help | -u | --username] username",
    "\t-h or --help\t顯示幫助資訊",
    "\t-u or --username\指定使用者名稱",
    "\t-r or --room\t指定房間"]
def help():
    for i in help_info:
        print i



def Send(sck, test):
    while True:
        data = raw_input('>')
        sck.send(data)
        if  data == "quit":
            break
def Recieve(sck, test):
    while True:
        data = sck.recv(BUFSIZ)
        if data == "quit":
            sck.close()
            break
        str = "\n" + data + "\n>" 
        stdout.write(str)

HOST = 'localhost'
PORT= 21567
BUFSIZ = 1024
ADDR = (HOST, PORT)
threads = []

if __name__ == "__main__":
    # 解析命令列引數
    try:
        opts, args = gnu_getopt(argv[1:], "hu:r:", ["help", "username=", "room="])        
    except GetoptError, err:
        print str(err)
        help()
        exit(2)
    username = ""
    room = ""
    for o, a in opts:
        if o in ("-h", "--help"):
            help()
            exit(0)
        elif o in ("-u", "--username"):
            username = a
        elif o in ("-r", "--room"):
            room = a
        else:
            print "未知選項"
            help()
            exit(2)
    if not username or not room:
        help()
        exit(2)
    chatCliSock = socket(AF_INET, SOCK_STREAM)
    chatCliSock.connect(ADDR)
    chatCliSock.send("%s %s" %(username, room))
    data = chatCliSock.recv(BUFSIZ)
    if data == "reuse":
        print "使用者%s已登入房間%s" %(username, room)
        raw_input()
        exit(1)
    elif data == "success":
        print "使用者%s成功登入房間%s" %(username, room)
        t = threading.Thread(target=Send, args = (chatCliSock, None))
        threads.append(t)
        t = threading.Thread(target=Recieve, args = (chatCliSock, None))
        threads.append(t)
        for i in range(len(threads)):
            threads[i].start()
        threads[0].join()

 

16.11.寫一個網頁客戶端。自己新建一個套接字,然後傳送http請求。

感覺難度不大。

 

#!/usr/bin/env python
#-*-coding:utf-8-*-

import socket,sys

website = sys.argv[1]
port = 80
print website

print "Creating socket...",
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
print "done."

print "Connecting to ...",
s.connect((website,port))
print "done."

s.send("GET /index.html HTTP/1.0\r\n\r\n")
data = s.recv(4096)
print data

 

 

16-12.休眠伺服器,在伺服器端上面加個sleep(num)就好,在這裡就不貼了。

16-13.功能太過複雜,本人渣渣,沒精力寫。

16-14.考慮的東西很多,水平有限,不做了。

16-15.非同步和SocketServer。這個用多執行緒可以實現,在《python網路程式設計基礎》上面直接有原始碼。使用方法都有教。

#!/usr/bin/env python
#-*- coding:utf-8 -*-

from SocketServer import ThreadingMixIn,TCPServer,StreamRequestHandler
import time

class TimeRequestHandler(StreamRequestHandler):
    def handle(self):
        req = self.rfile.readline().strip()
        if req == "asctime":
            result = time.asctime()
        elif req == "seconds":
            result = str(int(time.time()))
        elif req == "rfc822":
            result = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.gmtime())
        else:
            result = """
Unhandled request.Send a line with one of the following words:
asctime -- for human-readable time
seconds -- seconds since the Unix Epoch
rfc822 -- data/time in format used for mail and news posts
            """
        self.wfile.write(result + "\n")

class TimeServer(ThreadingMixIn,TCPServer):
    allow_reuse_address = 1

serveraddr = ('',8765)
srvr = TimeServer(serveraddr,TimeRequestHandler)
srvr.serve_forever()

 

 

 

轉載請註明出處http://www.cnblogs.com/sysu-blackbear/

 

多多指教!謝謝!

 

 

 

相關文章