1. 程式人生 > >python 網路程式設計攻略第一章 伺服器/客戶端互動栗子

python 網路程式設計攻略第一章 伺服器/客戶端互動栗子

server:

#!/usr/bin/env python
#--coding:utf8--
'''
簡單的回顯客戶端/伺服器應用
1.先建立一個TCP套接字
2.啟用重用地址
3.套接字繫結在本地裝置的指定埠
4.監聽階段,把backlog引數傳入listen()方法中
5.伺服器監聽多個客戶端。等待客戶端連線,向伺服器傳送一些資料。收到資料後,回顯資料給客戶端。
argparse是python用於解析命令列引數和選項的標準模組,用於代替已經過時的optparse模組
'''


import  socket,sys,argparse

host = 'localhost'
data_payload = 8192
backlog = 5

def echo_server(port):
    # Create a TCP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Enable reuse address/port
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    # Bind the socket to the port
    server_address = (host, port)
    sock.bind(server_address)
    # Listen to clients, backlog argument specifies the max no. of queued connections
    sock.listen(backlog)
    while True:
        print "Waiting to receive message from client"
        clientsocket, address = sock.accept()
        data = clientsocket.recv(data_payload)
        if data:
            print "client Data: %s" %data
            clientsocket.send(data)
            print "sent %s bytes back to %s" % (data, address)
        # end connection
        clientsocket.close()
if __name__ == '__main__':
    echo_server(port=8000)

client:

#!/usr/bin/env python
#--coding:utf8--

'''
簡單的回顯客戶端/伺服器應用
1.先建立一個TCP套接字
2.啟用重用地址
3.套接字繫結在本地裝置的指定埠
4.監聽階段,把backlog引數傳入listen()方法中
5.伺服器監聽多個客戶端。等待客戶端連線,向伺服器傳送一些資料。收到資料後,回顯資料給客戶端。
argparse是python用於解析命令列引數和選項的標準模組,用於代替已經過時的optparse模組
'''

import  socket,sys,argparse

host = 'localhost'
data_buff = 8192

def echo_client(port,message):
    """ A simple echo client """
    # Create a TCP/IP socket
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    # Connect the socket to the server
    server_address = (host, port)
    sock.connect(server_address)
    # Send data
    try:
        # Send data
        #message = "I'm client: This message will be echoed"
        print "Sending: %s" % message
        sock.sendall(message)
        # Look for the response
        while True:
            data = sock.recv(data_buff)
            print "Received for service: %s" % data
            sock.close()
    except socket.errno, e:
        print "Socket error: %s" %str(e)
    except Exception, e:
        print "Other exception: %s" %str(e)
    finally:
        print "Closing connection to the server"
        sock.close()

if __name__ == '__main__':
    port=8000
    message="I'm client: This message will be echoed"
    echo_client(port,message)