全部版块 我的主页
论坛 提问 悬赏 求职 新闻 读书 功能一区 学道会
452 0
2019-09-20
python网络编程攻略的3.7版本代理(原书是python2.7版本代码)
在windows下使用pycharm环境调试


第一章(不含1.10,1.11)


#!usr/bin/env python
#-*- coding:utf-8 _*-
\"\"\"
@author:Tony
@file: bNetwork.py
@time: 2019/09/{DAY}
\"\"\"
\"\"\"
socket.gethostname()
socket.gethostbyname()


\"\"\"

import socket
import sys
import argparse
import ntplib
from time import ctime
import struct



def print_machine_info():
    host_name = socket.gethostname()
    ip_address = socket.gethostbyname(host_name)
    print(\"Host name: \", host_name)
    print(\"IP address: %s\",ip_address)

def get_remote_machine_info():
    remote_host = \'www.python.org\'
    try:
        print(\"The %s IP address: %s\" %(remote_host, socket.gethostbyname(remote_host)))
    except socket.error as err_msg:
        print(\"%s: %s\" %(remote_host, err_msg))

def find_service_name():
    protocolname = \'tcp\'
    for port in [25,80]:
        print(type(port))
        print (\"Port: %s =>service name: %s\",port, socket.getservbyport(port,protocolname))
    print(\"Port: %s => service name: %s \" %(53,socket.getservbyport(53,\'udp\')))

# socket.ntohl()
# socket.htonl()
def convert_integer():
    data = 1234
    print(\"The bin number is: \", bin(data))
    # 32-bit
    print(\"Original: %s => Long host byte order: %s, Network byte order: %s\" \\
           %(data,socket.ntohl(data),socket.htonl(data)))
    # 16-bit
    print(\"Original: %s => Short host byte order: %s, Network byte order: %s\" \\
           %(data, socket.ntohs(data), socket.htons(data)))


def server_feedback():
    # setup argument parsing
    # 使用argparse模块把命令行参数传入脚本以及在脚本中解析命令行参数
    # E:\\PythonR_D\\network\\a2019_09_19\\venv>python bNetwork.py --host=www.python.org --port=8080 --file=bNetwork.py
    # Connection error: [WinError 10060] 由于连接方在一段时间后没有正确答复或连接的主机没有反应,连接尝试失败。
    parser = argparse.ArgumentParser(description=\'Socket Error Examples\')
    parser.add_argument(\'--host\',action=\"store\", dest=\"host\", required=False)
    parser.add_argument(\'--port\', action=\"store\",dest=\"port\", type=int, required=False)
    parser.add_argument(\'--file\', action=\"store\", dest=\"file\", required=False)
    given_args = parser.parse_args()
    host = given_a

1.14客户端
#!usr/bin/env python
#-*- coding:utf-8 _*-
\"\"\"
@author:Lenovo
@file: program114_C.py
@time: 2019/09/{DAY}
\"\"\"
import socket
import sys
import argparse
host = \'localhost\'


def echo_client(port):
    \"\"\" 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)
    print (\"Connecting to %s port %s\" % server_address)
    sock.connect(server_address)
    # Send data
    try:
        # Send data
        message = (\"Test message. This will be echoed\")
        print (\"Sending %s\" % message)
        #需要在sendall的类型做转换encode(encoding=\'utf-8\')
        sock.sendall(message.encode(encoding=\'utf-8\'))
        # Look for the response
        amount_received = 0
        amount_expected = len(message)
        while amount_received < amount_expected:
            data = sock.recv(16)
            amount_received += len(data)
            print (\"Received: %s\" % data)
    except socket.errno as e:
        print (\"Socket error: %s\" %str(e))
    except Exception as e:
        print (\"Other exception: %s\" %str(e))
    finally:
        print (\"Closing connection to the server\")
        sock.close()

if __name__ == \'__main__\':
    parser = argparse.ArgumentParser(description=\'Socket Server Example\')
    parser.add_argument(\'--port\', action=\"store\", dest=\"port\", type=int,required=True)
    given_args = parser.parse_args()
    port = given_args.port
    echo_client(port)


1.14服务器端
#!usr/bin/env python
#-*- coding:utf-8 _*-
\"\"\"
@author:Tony
@file: program114.py
@time: 2019/09/{DAY}
\"\"\"
import socket
import sys
import argparse
host = \'localhost\'
data_payload = 2048
backlog = 5


def echo_server(port):
    \"\"\" A simple echo server \"\"\"
    # 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)
    print (\"Starting up echo server on %s port %s\" % server_address)
    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\")
        client, address = sock.accept()
        data = client.recv(data_payload)
        if data:
            print (\"Data: %s\" %data)
            client.send(data)
            print (\"sent %s bytes back to %s\" % (data, address))
        # end connection
        client.close()


if __name__ == \'__main__\':
    parser = argparse.ArgumentParser(description=\'Socket Server Example\')
    parser.add_argument(\'--port\', action=\"store\", dest=\"port\", type=int,required=True)
    given_args = parser.parse_args()
    port = given_args.port
    echo_server(port)
tmp_80f1b2040e03724f5c215608a6317dd6397309b303b01879.jpg tmp_01b94f75a67106dab7b1e8a1e13da8de9fb6f0010a03dc9b.jpg
二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

栏目导航
热门文章
推荐文章

说点什么

分享

扫码加好友,拉您进群
各岗位、行业、专业交流群