zoukankan      html  css  js  c++  java
  • python3 TCP协议下的socket

    --------------------------------------tcp_server.py--------------------------------------
    
    # coding:utf-8
    import socket
    
    server = socket.socket()  # 创建socket对象
    ip_port = ("127.0.0.1", 8001)  # ip地址和端口号
    server.bind(ip_port)  # 绑定ip地址和端口号
    server.listen(2)  # 监听ip地址和端口号
    conn, addr = server.accept()  # 创建连接通道,接收客户端的连接, conn为客户端和服务端的通道,addr为客户端的IP和端口号
    print("conn:", conn)
    print("addr:", addr)
    from_client_msg = conn.recv(1024)  # 通过通道接收来自客户端的消息,最大为1024B,消息为bytes类型
    from_client_msg = from_client_msg.decode("utf-8")
    print("来自客户端的消息:", from_client_msg)
    server_input = input(">>>: ").strip()
    conn.send(server_input.encode("utf-8"))  # 通过通道发送消息,消息类型为bytes
    conn.close()  # 关闭通道
    server.close()  # 关闭socket连接
    
    
    --------------------------------------tcp_client.py--------------------------------------
    
    # coding:utf-8
    import socket
    
    client = socket.socket()  # 创建socket对象
    ip_port = ("127.0.0.1", 8001)  # 服务端IP和端口号
    client.connect(ip_port)  # 根据IP和端口号连接服务端
    client_input = input(">>>: ").strip()
    client.send(client_input.encode("utf-8"))  # 发送消息给服务端
    from_server_msg = client.recv(1024)  # 接收来自服务端的消息,最大为1024B,数据类型为bytes
    print("来自服务端的消息: ", from_server_msg.decode("utf-8"))
    client.close()  # 关闭连接
  • 相关阅读:
    【2017-5-24】WebForm 条件查询
    【2017-5-24】WebForm 分页功能
    【2017-5-22】Application ViewState RepeaterCommand用法
    【2017-5-21】问题总结 Session,Cookie,登录状态保持
    【2017-5-20】传值基础 复合控件
    【2017-5-18】WebForm Repeater的使用 简单控件
    JavaScript Bind()趣味解答 包懂~~
    无题
    移动端横屏(beta)
    常用CSS居中
  • 原文地址:https://www.cnblogs.com/lilyxiaoyy/p/10926987.html
Copyright © 2011-2022 走看看