Python____TCP通信
Posted zwl1024
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python____TCP通信相关的知识,希望对你有一定的参考价值。
2019-11-21
10:54:33
TCP客户端:
import argparse, socket,sys import time # socket.setdefaulttimeout(20) def recvall(sock, length): data = b‘‘ while len(data) < length: more = sock.recv(length - len(data)) if not more: raise EOFError(‘总共有%dbytes,但只收到了%dbytes‘ % (length, len(data))) data += more return data if __name__ == ‘__main__‘: sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.connect((‘192.168.137.1‘, 10000)) print(‘客户的分配了socket:‘, sock.getsockname()) i=0 for x in range(4): # try: text = ‘我是客户端你是服务器嚯嚯嚯!‘.encode(‘utf-8‘) i=i+len(text) sock.sendall(text) sys.stdout.flush() print("已发送:",i) # except ConnectionResetError: # pass sock.shutdown(socket.SHUT_WR) num = 0 while True: reply = sock.recv(48) # b‘Farewell, client‘的长度 num += len(reply) print(‘接收:‘,num) if not reply: print("ok") break # print(‘服务器返回:‘, reply.decode(‘utf-8‘)) print("理论上应该关闭sock") sock.close() time.sleep(1)
TCP服务端:
import argparse, socket,sys def recvall(sock, length): data = b‘‘ while len(data) < length: more = sock.recv(length - len(data)) if not more: raise EOFError(‘总共有%dbytes,但只收到了%dbytes‘ % (length, len(data))) data += more return data if __name__ == ‘__main__‘: sc = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sc.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sc.bind((‘‘, 10000)) sc.listen() print(‘正在侦听{}...‘.format(sc.getsockname())) num = 0 while True: scc, address = sc.accept() print(‘连接来自:‘, address) print(‘socket名字:‘, scc.getsockname()) print(‘socket peer:‘, scc.getpeername()) while True: message = scc.recv(42)#recvall(scc, 24) # 尝试 12,,20,28会是什么结果 if not message: break # print(‘收到16-octet消息:‘, repr(message)) print(‘收到16-octet消息:‘, (message.decode(‘utf-8‘))) scc.sendall(message) sys.stdout.flush() num += len(message) print("已发送:",num) scc.close() print(‘应答发送,socket关闭‘) sc.close()
以上是关于Python____TCP通信的主要内容,如果未能解决你的问题,请参考以下文章
Python学习笔记__16.1章网络编程——TCP/IP简介
阶段1 语言基础+高级_1-3-Java语言高级_07-网络编程_第2节 TCP协议_1_TCP通信的概述(上)