第十一章:网络通信-socket:网络通信-TCP/IP客户和服务器-简易客户连接

11.2.2.4 简易客户连接
如果使用便利函数create_connection()来连接服务器,那么TCP/IP客户可以省去几步。这个函数只有一个参数,这是一个包含服务器地址的二值元组,函数将由这个参数推导出用于连接的最佳地址。

import socket
import sys

def get_constants(prefix):
    """Create a dictionary mapping socket module
    constants to their names.
    """
    return {
        getattr(socket,n):n
        for n in dir(socket)
        if n.startswith(prefix)
        }

families = get_constants('AF_')
types = get_constants('SOCK_')
protocols = get_constants('IPPROTO_')

# Create a TCP/IP socket.
sock = socket.create_connection(('localhost',10000))

print('Family  :',families[sock.family])
print('Type    :',types[sock.type])
print('Protocol:',protocols[sock.proto])
print()

try:
    # Send data.
    message = b'This is the message. It will be repeated.'
    print('sending {!r}'.format(message))
    sock.sendall(message)

    amount_received = 0
    amount_expected = len(message)
    while amount_received < amount_expected:
        data = sock.recv(16)
        amount_received += len(data)
        print('received {!r}'.format(data))

finally:
    print('closing socket')
    sock.close()

create_connection()使用getaddrinfo()查找候选连接参数,并返回一个打开的socket,这是能成功创建一个连接的第一个配置。可以检查family,type和proto属性来确定返回的socket的类型。
运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值