2020撸python--socket编程

"""
    Socket编程
"""
import sys
import socket

def server_func(port):
    """
        服务端
    """
    # 创建socket对象
    server = socket.socket()
    # 绑定ip和端口
    server.bind(("127.0.0.1", port))
    # 监听是否有客户端连接
    server.listen(10)

    # 接收客户端连接
    sock_obj, address = server.accept()
    sock_obj.settimeout(3)

    while True:
        try:
            recv_data = sock_obj.recv(1024).decode("utf-8")
            if recv_data == "quit":
                break
            # 给客户端回复消息
            send_data = 'reveived[%s]' % recv_data
            sock_obj.send(send_data.encode("utf-8"))
        except Exception as excep:
            print("error:", excep)
    # 关闭socket对象
    sock_obj.close()
    server.close()

def client_func(port):
    """
        客户端
    """
    # 创建客户端的socket对象
    client = socket.socket()
    # 连接服务端,需要指定端口和ip
    client.connect(("127.0.0.1", port))

    while True:
        # 给服务端发送数据
        send_data = input("客户端》").strip()
        client.send(send_data.encode("utf-8"))
        if send_data == "quit":
            break
        # 获取服务端返回的消息
        recv_data = client.recv(1024).decode("utf-8")

    client.close()


if __name__ == '__main__':
    flag = sys.argv[1]
    if flag == "server":
        server_func(5001)
    else:
        client_func(5001)

 

你可能感兴趣的:(2020撸python--socket编程)