当前位置:   article > 正文

TCP_Server_tcp server

tcp server
import socket
import threading


# 指定本地端口
IP = '0.0.0.0'
PORT = 9998

def main():
    server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # IPV4, TCP服务
    server.bind((IP, PORT))
    server.listen(5)  # 指定最大连接数量
    print(f'[*] 当前监听: {IP}:{PORT}')

    while True:
        client, address = server.accept()  # 将接收到的客户端socket对象保存到client变量中,远程连接信息传入adress当中
        print(f'[*] 接收连接来自:{address[0]}:{address[1]}')
        # 创建一个新的线程,指向handler_client函数,并传入client对象,
        # 需要在变量 client 之后添加一个逗号。只发送 client toargs= ()是尝试解包多个参数,而不是只发送一个参数
        client_handler = threading.Thread(target=handler_client, args=(client,)) 
        print('[*] 线程已启动')
        client_handler.start()  # 启动该线程

def handler_client(client_socket):
    with client_socket as sock:
        request = sock.recv(1024)  # 接收数据
        print(f'[*] 已接收: {request.decode("utf-8")}')
        sock.send(b'ACK')

if __name__ == "__main__":
    main()


  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/运维做开发/article/detail/978226
推荐阅读
相关标签
  

闽ICP备14008679号