Python客户端不会重新连接到服务器

时间:2019-01-17 19:39:40

标签: python sockets server client

自从过去3天以来,我一直在尝试纠正此错误,而我渐渐厌倦了它,有人可以指出我正确的方向吗?

所以,我写了2个脚本,一个是服务器,另一个是客户端

Server.py

#!/usr/python

import socket
import os

port = 3000

def clear():
    os.system('clear')
    print("-:-:-:-:-:Server:-:-:-:-:-")

#Starting Server
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = socket.gethostname()
serversocket.bind((host, port))
serversocket.listen(1)

clear()

clientsocket, addr = serversocket.accept()
print("Connection from: " + str(addr))
while True:
    msg = raw_input(" ->")

    if msg == "help":
        clear()
        print("+-----------------------------------+")
        print("|             Help Menu             |")
        print("+-----------------------------------+")      
        print("|   help       -   shows help menu  |")
        print("+-----------------------------------+")
        print("|   clear      -   clears           |")
        print("+-----------------------------------+")
        raw_input("Press ANY key to return")
        clear()
    elif msg == "clear":
        clear()
    else:
        msg = str(msg).encode("UTF-8")
        clientsocket.send(msg)
        msg = clientsocket.recv(4096)
        print(msg.decode("UTF-8"))

Client.py

#!/usr/python

import socket
import time

def send(msg):
    try:
        s.send(msg.encode("UTF-8"))
    except:
        Connect()

def getInstructions():
    try:
        while True:
            msg = s.recv(4096)
            inst = msg.decode("UTF-8")
            time.sleep(5)
            send("!")
    except:
        Connect()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()

def Connect():
    try:
        print("Connect() connecting to: "+ str(host) + str(3000)) 
        s.connect((host, 3000))
        getInstructions()
    except:
        time.sleep(1)
        print("Connect() Exception")
        Connect()
Connect()

简而言之,我的程序要做的是

服务器启动并等待传入​​流量

客户端启动并将流量发送到服务器

如果服务器无法接收到该消息,则客户端每5秒发送一个字符串(在本例中为“!”),客户端正在尝试重新连接到服务器,这就是问题所在,客户端没有重新连接,它卡在了Connect()循环,因为它无法再重新连接

我尝试在重新连接时始终创建一个新的套接字

Client.py

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()

    def Connect():
        try:
            print("Connect() connecting to: "+ str(host) + str(3000))
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            s.connect((host, 3000))
            getInstructions()
        except:
            time.sleep(1)
            print("Connect() Exception")
            Connect()

这似乎以某种方式解决了该问题,客户端能够重新连接到服务器,但是此行确实使代码更破了,客户端被服务器显示为已连接,但是客户端没有收到任何发送的数据。

还有其他可能要说的好话,那就是客户端连接到服务器,然后我停止服务器,客户端进入“重新连接模式”,然后我再次启动服务器,没有任何反应,客户端是仍在尝试重新连接(但失败)。现在,我必须重新启动客户端才能重新连接,这真的不是我正在寻找的东西。

2 个答案:

答案 0 :(得分:1)

我终于..最后!找到了这没用的原因.. (我不是专家,所以也许有人可以将其更改为更“准确”)

我创建了一个TCP套接字连接,该连接的连接详细信息可能完全保存在变量s

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

对于连接细节,我是说它自己可能是这样的,例如,服务器具有不会更改太多的静态细节(端口3000上的192.168.2.100),但是客户端不使用该特定端口与之通信,客户端采用了一些随机端口,可用,由于某种原因,这就是客户没有工作的原因   (但同样,那只是我的论点,我对此并不了解。)

但这是我改变的地方

Client.py

#Connection
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()

def Reconnect():  #Ive created a new function called Reconnect, because, .., well it works fine for now
    try:
        global s #Its accessing the global socket variable
        s = ""   #blanks it out (not sure if i have to blank it out)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # create again a new socket
        s.connect((host, port)) # It tries to connect again
        getInstructions() # done~
    except:
        time.sleep(1)
        print("Reconnecting")
        Reconnect()

def Connect():
    try:
        print("Connect() connecting to: "+ str(host) + str(port)) 
        s.connect((host, port))
        getInstructions()
    except:
        time.sleep(1)
        print("Connect() Exception, trying to Reconnect()")
        Reconnect()

但这就是为什么我如此热爱编程的原因,它当然是2片刀,但该死的,感觉是在用10秒的时间解决了一个愚蠢的错误之后得到的。值得打字

答案 1 :(得分:0)

服务器需要接收命令。

Server.py

import socket
import os

port = 3000

#Starting Server
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
host = socket.gethostname()
serversocket.bind((host, port))
serversocket.listen(1)

clientsocket, addr = serversocket.accept()
print("Connection from: " + str(addr))

clientsocket.send("-:-:-:-:-: Connected in theServer :-:-:-:-:-")

def menuHelp():
    clientsocket.send("\
+-----------------------------------+ \n \
|             Help Menu             | \n \
+-----------------------------------+ \n \
|   help       -   shows help menu  | \n \
+-----------------------------------+ \n \
|   clear      -   clears           | \n \
+-----------------------------------+")

while True:
    msg = clientsocket.recv(4096)
    msg = msg.decode("UTF-8")

    if msg == "help":
        menuHelp()
    elif msg == "clear":
        clientsocket.send("Command Clear\n")
    else:
        clientsocket.send("invalid option\n")
        menuHelp()

和客户。

Client.py

import socket
import time

def send(msg):
    try:
        s.send(msg.encode("UTF-8"))
    except:
        Connect()

def getInstructions():
    try:
        msg = s.recv(4096)
        print(msg.decode("UTF-8"))
        input("Press ANY key to return")
    except:
        Connect()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()

def Connect():
    try:
        print("Connect() connecting to: "+ str(host) + str(3000)) 
        s.connect((host, 3000))
        send("help")

        while True:
            getInstructions()       
            cli = input(" ->")
            send(cli)
    except:
        time.sleep(1)
        print("Connect() Exception")
        Connect()
Connect()
相关问题