python asyncio tcp server_如何处理python asyncio中的tcp客户端套接字自...

您可以通过简单地遍历try / except语句来处理重新连接.

此外,asyncio.wait_for可用于设置读取操作的超时.

考虑以下工作示例:

import asyncio

async def tcp_client(host, port):

reader, writer = await asyncio.open_connection(host, port)

try:

while not reader.at_eof():

data = await asyncio.wait_for(reader.read(100), 3.0)

print('raw data received: {}'.format(data))

finally:

writer.close()

async def tcp_reconnect(host, port):

server = '{} {}'.format(host, port)

while True:

print('Connecting to server {} ...'.format(server))

try:

await tcp_client(host, port)

except ConnectionRefusedError:

print('Connection to server {} failed!'.format(server))

except asyncio.TimeoutError:

print('Connection to server {} timed out!'.format(server))

else:

print('Connection to server {} is closed.'.format(server))

await asyncio.sleep(2.0)

async def main():

servers = [('localhost', 8888), ('localhost', 9999)]

coros = [tcp_reconnect(host, port) for host, port in servers]

await asyncio.gather(*coros)

if __name__ == '__main__':

loop = asyncio.get_event_loop()

loop.run_until_complete(main())

loop.close()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于题目要求构造TCP头部,因此需要使用原始套接字发送数据包。以下是一个简单的Python程序,它构造了一个包含IP头部、UDP头部和TCP头部的TCP数据包,并使用原始套接字将其发送到目标主机。 ``` import socket import struct # 构造IP头部 source_ip = '192.168.1.100' dest_ip = '192.168.1.200' ip_ver = 4 ip_ihl = 5 ip_dscp = 0 ip_ecn = 0 ip_ttl = 255 ip_proto = socket.IPPROTO_UDP ip_id = 54321 ip_frag_offset = 0 ip_header = struct.pack('!BBHHHBBH4s4s', (ip_ver << 4) + ip_ihl, ip_dscp << 2 + ip_ecn, ip_ihl + 20, ip_id, ip_frag_offset << 13, ip_ttl, ip_proto, 0, source_ip, dest_ip) # 构造UDP头部 udp_src_port = 1234 udp_dest_port = 5678 udp_len = 8 + 20 + 20 # UDP头部长度 + IP头部长度 + TCP头部长度 udp_checksum = 0 udp_header = struct.pack('!HHHH', udp_src_port, udp_dest_port, udp_len, udp_checksum) # 构造TCP头部 tcp_src_port = 1234 tcp_dest_port = 80 tcp_seq = 0 tcp_ack_seq = 0 tcp_doff = 5 # 数据偏移量,即TCP头部长度 tcp_flags = 0x02 # SYN标志位 tcp_window = socket.htons(5840) tcp_checksum = 0 tcp_urg_ptr = 0 tcp_offset_res = (tcp_doff << 4) + 0 tcp_header = struct.pack('!HHLLBBHHH', tcp_src_port, tcp_dest_port, tcp_seq, tcp_ack_seq, tcp_offset_res, tcp_flags, tcp_window, tcp_checksum, tcp_urg_ptr) # 构造TCP数据包 packet = ip_header + udp_header + tcp_header # 发送数据包 s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_RAW) s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) s.sendto(packet, (dest_ip, 0)) ``` 请注意,由于这是一个构造TCP数据包的示例,因此代码只设置了SYN标志位,其他标志位应根据需要进行设置。此外,由于使用了原始套接字,因此需要以root权限运行此程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值