码迷,mamicode.com
首页 > 编程语言 > 详细

Python____TCP通信

时间:2019-11-21 12:19:14      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:form   flush   col   exce   nbsp   服务   range   pass   消息   

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通信

标签:form   flush   col   exce   nbsp   服务   range   pass   消息   

原文地址:https://www.cnblogs.com/zwl1024/p/11904226.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!