zoukankan      html  css  js  c++  java
  • 170925_1 Python socket 创建TCP的服务器端和客户端

    【Python版本】3.6

    【遇到的问题】

    客户端和服务器端都遇到:TypeError: a bytes-like object is required, not 'str'

    【解决方案】

    参考:https://stackoverflow.com/questions/13274553/python-3-3-socket-typeerror

    创建TCP服务器端:

     1 from socket import *
     2 from time import ctime
     3 
     4 host = ''
     5 port = 21563
     6 buf_size = 1024
     7 addr = (host, port)
     8 
     9 
    10 tcpSerSock = socket(AF_INET, SOCK_STREAM)
    11 tcpSerSock.bind(addr)
    12 tcpSerSock.listen(5)
    13 
    14 while True:
    15     print("waiting for connection....")
    16     tcpCliSock, ADDR = tcpSerSock.accept()
    17     print("...connected from:", ADDR)
    18 
    19     while True:
    20         data = tcpCliSock.recv(buf_size)
    21         print(data)
    22         print(bytes(ctime(), 'utf-8'))
    23         if not data:
    24             break
    25         response = '[%s] %s' % (ctime(), data.decode('utf-8'))
    26         tcpCliSock.send(response.encode('utf-8'))
    27     tcpCliSock.close()
    28 
    29 tcpSerSock.close()

    创建TCP客户端:

     1 from socket import *
     2 
     3 
     4 host = 'localhost'
     5 port = 21563
     6 buf_size = 1024
     7 addr = (host, port)
     8 
     9 tcpCliSock = socket(AF_INET, SOCK_STREAM)
    10 tcpCliSock.connect(addr)
    11 
    12 while True:
    13     data = input('>')
    14 
    15     if not data:
    16         break
    17     tcpCliSock.send(data.encode('utf-8'))
    18     data = tcpCliSock.recv(buf_size)
    19     if not data:
    20         break
    21     print(data.decode())
    22 
    23 tcpCliSock.close()
  • 相关阅读:
    C#中,对Equals()、ReferenceEquals()、==的理解
    C#语言中的Main()可以返回int值
    C#中支持的运算符
    C#中,对象格式化的理解
    正则表达式
    .NET三年
    C#中,可重载的运算符
    c#中,const成员和readonly成员的区别
    c#中,struct和class的区别
    jQuery制作图片旋转效果
  • 原文地址:https://www.cnblogs.com/catleer/p/7591764.html
Copyright © 2011-2022 走看看