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()

相关推荐