Python TCP通信客户端服务端代码实例
这篇文章主要介绍了Python TCP通信客户端服务端代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
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()
相关推荐
digwtx 2020-09-14
FlySky 2020-11-02
逍遥友 2020-10-26
taiyangshenniao 2020-10-05
flycony 2020-09-23
jacktangj 2020-09-18
YENCSDN 2020-09-15
lsjweiyi 2020-09-14
拾毅者 2020-09-14
zlxcsdn 2020-09-13
weiiron 2020-08-17
amazingbo 2020-08-16
郗瑞强 2020-08-16
lispython 2020-08-16
fengling 2020-08-15
xiesheng 2020-08-02
葫芦小金刚 2020-07-28
StevenSun空间 2020-07-26