简体   繁体   English

一个连接/命令后,Python套接字关闭

[英]Python Socket Closes after One Connection/Command

The Client and Server can successfully connect however only one command can be issued. 客户端和服务器可以成功连接,但是只能发出一个命令。 Been at this for a while and wanted some outside help, any feedback or suggested improvements would be great thanks in advance. 来到这里已经有一段时间了,希望得到外界的帮助,在此先感谢您的任何反馈或建议的改进。

Been looking at other posts which suggest I may have prematurely closed the connection but I don't believe this to be true due to the fact the program doesn't throw any disconnection errors though I may be wrong. 一直在查看其他暗示我可能过早关闭连接的帖子,但我不认为这是真的,因为尽管我可能是错误的,但程序不会引发任何断开连接错误。

client.py client.py

import socket
import sys
import os

# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

##server = input("Enter server IP: ")
##print(server)
##
##port = int(input("Enter port: "))
##print(port)

def send_msg(msg):
    sock.sendall(msg.encode())

def get_msg():
    msg = sock.recv(2048).decode()
    return msg

server = "127.0.0.1"
port = 100

sock.connect((server, port))
print("Connecting to " + server + " on port " + str(port) + "\n")

while True:
    #Send data
    msg = input(os.getcwd() + "> ")
    print("Sending '" + msg + "'")
    send_msg(msg)

    #Response
    #amnt_exp = len(msg)
    #data = sock.recv(2048)
    data = get_msg()

    if data == "exit":
        print("\nClosing connection")
        sock.close()
    else:
        print("Received: \n" + data)

server.py server.py

import socket
import sys
import os
import subprocess

#Create a TCP/IP Socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

##server = input("Enter server IP: ")
##print(server)
##
##port = int(input("Enter port: "))
##print(port)

def send_msg(msg):
    conn.sendall(msg.encode())

def get_msg():
    msg = conn.recv(2048).decode()
    return msg

server = "127.0.0.1"
port = 100

#Config
sock.bind((server, port))
print("Bound to " + server + " on port " + str(port) + "\n")


sock.listen(1)
print("Waiting for a connection...")
while True:
    conn, caddr = sock.accept()
    print("Connected!\n")
    print("Waiting for a command...")

    #data = conn.recv(2048).decode()
    data = get_msg()

    #Exit
    if data == "exit":
        print("\nConnection closed")
        conn.close()

    print("Received '" + data + "'")
    #Command Exec
    call = subprocess.Popen(data, stdout = subprocess.PIPE, shell=True)

    #Output
    output, err = call.communicate()
    call_status = call.wait()

    #print("Output: ", output)
    #print("Exit status: ", call_status)

    #Reply
    msg = "Command successful\n" + "Output: " + str(output) + "\n" + "Exit status:" + str(call_status) 
    print("Sending reply...")
    print("\nWaiting for a command...")
    send_msg(msg)

The problem is that your server loop only accepts a single command, and then it goes back to accept a whole new connection, and never looks at the old connection again. 问题在于您的服务器循环仅接受一个命令,然后返回accept一个全新的连接,而不再查看旧的连接。

Your output is pretty misleading, because it does print out Waiting for a command... . 您的输出很容易引起误解,因为它确实会打印出Waiting for a command... But that's only happening because you have an extra print("\\nWaiting for a command...") before send_msg , and you don't have any output before sock.accept . 但是,这只是发生,因为你有一个额外print("\\nWaiting for a command...")之前send_msg ,和你没有之前的任何输出sock.accept You can see what's actually happening if you make your prints accurate. 如果您使打印准确,则可以看到实际发生的情况。 For example: 例如:

sock.listen(1)
while True:
    print('Waiting for a connection...') # inside the loop, not before it
    conn, caddr = sock.accept()
    # ... etc. ...
    print("Sending reply...")
    # Don't print Waiting for a command here, because you aren't
    send_msg(msg)
    # And print something after the send succeeds
    print("Sent")
    print()

So, now you know what's wrong, how do you fix it? 那么,现在您知道出了什么问题,该如何解决?

Simple. 简单。 We just need a nested loop. 我们只需要一个嵌套循环。 Once you accept a client connection, keep using that connection until they exit: accept客户端连接后,请继续使用该连接,直到它们退出:

sock.listen(1)
while True:
    print('Waiting for a connection...') # inside the loop, not before it
    conn, caddr = sock.accept()
    print("Connected!\n")

    while True:
        print("Waiting for a command...")
        data = get_msg()

        #Exit
        if data == "exit":
            print("\nConnection closed")
            conn.close()
            break # go back to the outer accept loop to get the next connection

        print("Received '" + data + "'")
        # ... etc. ...
        print()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM