相互数据传输(Python套接字编程) [英] Mutual data transfer (Python socket programming)

查看:82
本文介绍了相互数据传输(Python套接字编程)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好。我是一个初学者,试图完成一个关于网络的项目。我正在研究服务器 - 客户端二人组,我发现了很多障碍。由于我完全缺乏知识和经验,他们中的大多数都给我带来了问题,所以我想这次也是如此。我设法创建了一个可以向客户端发送命令的服务器。客户端当前能够执行命令,检查它是否正确执行,但现在我尝试向服务器发送响应,这就是我遇到麻烦的地方。我无法想象怎么做。我将在下面发布我的代码。我会非常感激任何形式的帮助。我想知道如何强制它发送并收到回复。我很抱歉因为这些琐事而浪费你的时间,但我希望有人愿意向我展示正确的方向。提前感谢您,祝您有个愉快的一天。



我尝试过的事情:



服务器:



Hello. I'm a beginner trying to finish one project concerning networking. I'm working on a server-client duo, and i found a lot of obstacles. Most of them caused problems to me only due to my complete lack of knowledge and experience, so i guess that's the case also this time. I've managed to create a server which can send commands to a client. Client is currently able to execute a command, check if it was executed correctly, but now i try to send a response to a server, and that's where i have troubles. I can't figure how to do it. I will post my code down below. I would be immensely grateful for any sort of help. I'd like to know how to force it to send and recieve a response. I'm sorry for wasting your times for such trivialities, but i hope someone will want to show me the right direction. Thank you in advance and have a nice day.

What I have tried:

Server:

import socket


def socket_create():
    try:
        global host
        global port
        global s
        host = ''
        port = 9999
        s = socket.socket()
    except socket.error as msg:
        print("Socket creation error: " + str(msg))


print("Test server")


def socket_bind():
    try:
        global host
        global port
        global s
        s.bind((host, port))
        print("Binding...")
        s.listen(5)
    except socket.error as msg:
        print("Binding error: " + str(msg) + "\n" + "Retrying...")
        socket.bind()


def socket_accept():
    conn, address = s.accept()
    print("Connection established | " + "IP " + address[0] + " | Port " + str(address[1]))
    print("Give the command: ")
    send_command(conn)
    receive_command()  #try

    conn.close()


def send_command(conn):
    while True:
        cmd = input()
        if len(str.encode(cmd)) > 0:
            conn.send(str.encode(cmd))
            

#try
def receive_command():
    while True:
        resp = s.recv(1024)
        if resp[:1].decode("ISO-8859-1") == 'e':
            print("test")


def main():
    socket_create()
    socket_bind()
    socket_accept()


main()





客户:





Client:

import pyautogui
import os
import socket
import threading
import time

s = socket.socket()
host = '' #place for ip
port = 9999
s.connect((host, port))

print("Test client")

path = 'D:/screen'
os.chdir(path)


def sender1():
    conn, address = s.accept()
    responder1(conn)

    conn.close()


def printer1():
    pyautogui.screenshot('D:/screen/screenshot1.png')
    if os.path.isfile('./screenshot1.png'):
        print("Screenshot1 was created")
    else:
        print("Screenshot1 was not created")


def printer2():
    pyautogui.screenshot('D:/screen/screenshot2.png')
    if os.path.isfile('./screenshot2.png'):
        print("Screenshot2 was created")
    else:
        print("Screenshot2 was not created")


def responder1():
    if os.path.isfile('./screenshot1.png'):
        s.send(str.encode("e"))


def responder2():
    if os.path.isfile('./screenshot2.png'):
        print("test 2")
    else:
        print("n. test 2")


t1 = threading.Thread(target=printer1, name='thread1')
t2 = threading.Thread(target=printer2, name='thread2')
t3 = threading.Thread(target=responder1, name='thread3')
t4 = threading.Thread(target=responder2, name='thread4')

while True:
    command = s.recv(1024)
    print(command)   #delete after test
    if command[:1].decode("ISO-8859-1") == 'a':
        t1.start()
        time.sleep(2)
        t3.start()
    if command[:1].decode("ISO-8859-1") == 'b':
        t2.start()
        time.sleep(2)
        t4.start()

s.close()

推荐答案

这看起来比你的代码更好:



Python中的套接字编程(指南) - 真正的Python [ ^ ]
This looks better than your code:

Socket Programming in Python (Guide) – Real Python[^]


这篇关于相互数据传输(Python套接字编程)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆