Python 网络编程

rpc_server.py

# coding=UTF-8
import socket

HOST = "192.168.0.103"
PORT = 1122

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind((HOST, PORT))
sock.listen(10)  # 监听客户端连接
while True:
    conn, addr = sock.accept()  # 接收一个客户端连接
    print str(addr) + "已经连接"
    cmd = conn.recv(1024);
    if len(cmd) != 0:
        res = "\n"
        if cmd == "open":
            res = '打开'
        elif cmd == 'close':
            res = "关闭"
        elif cmd == "update":
            res = "更新"
        else:
            res = "未知命令"
        print res
        conn.sendall(res + "\n")  # 将响应发送到发送缓冲 send buffer
    else:
        conn.sendall(b"服务端未接收到指令")
    # 关闭连接
    conn.close()

rpc_client.py

# coding=UTF-8
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("192.168.0.104", 5454))  # 连接服务器
sock.sendall(b"hello")  # 将消息输出到发送缓冲 send buffer
print(sock.recv(1024))  # 从接收缓冲 recv buffer 中读响应
sock.close()  # 关闭套接字...

posted @ 2021-03-29 12:33  巫鸦  阅读(58)  评论(0编辑  收藏  举报