Python socket 片段代码示例

初学socket 觉得很有趣,下面是刚刚学习的代码,提供出来,给大家一起学习一下

首先展示的是服务器端的代码:

import socket
import os
server = socket.socket()

server.bind(('localhost',6960))
print("我要开始等电话了")
server.listen()
while True:
    conn,addr = server.accept()
    print(conn,addr)
    print("电话来了")
    while True:
        print("等待新的指令")
        data = conn.recv(1024)
        if not data:
            print("客服端已断开")
            break
        print("recv:",data)
        cmd_res = os.popen(data.decode()).read()
        print("brfore send",len(cmd_res))
        if len(cmd_res) == 0:
            cmd_res = "cmd has no output"
        conn.send(str(len(cmd_res)).encode("utf-8")) #先发大小给客服端
        conn.send(cmd_res.encode("utf-8"))
        print("send done")
server.close()

接下来是客服端的代码:

import socket
import os

client = socket.socket()
client.connect(('localhost',6960))

while True:
    msg = input(">>>:").strip()
    if len(msg) == 0:continue

    client.send(msg.encode("utf-8")) #
    data_size = client.recv(1024) #介绍命令结果的大小
    print("命令结果大小:",data_size)
    received_size = 0
    received_data = b''
    while received_size < int(data_size.decode()):
        data = client.recv(1024)
        received_size += len(data) #每次手打的有肯能小于1024,所以必须用len判断
        #print(data.decode())
        received_data += data
    else:
        print("cmd_res receive done",received_size)
        print(received_data.decode())
    #data = client.recv(1024)
    #print("recv",data.decode())
client.close()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值