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)


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐