[英]My Python socket server can only receive one message from the client
Hi i got a problem with my socket server or the client the problem is i can only send one message from the client to the server then the server stops receiving for some reason i want it to receive more then one. 嗨,我的套接字服务器或客户端出现问题,问题是我只能从客户端向服务器发送一条消息,然后服务器由于某种原因停止接收,我希望它接收到的消息多于一个。
Server.py Server.py
import socket
host = ''
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
print ("Connection from", addr)
while True:
databytes = conn.recv(1024)
if not databytes:
break
data = databytes.decode('utf-8')
print("Recieved: "+(data))
if data == "dodo":
print("hejhej")
if data == "did":
response = ("Command recived")
conn.sendall(response.encode('utf-8'))
conn.close()
client.py client.py
import socket
host = '127.0.0.1'
port = 1010
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))
print("Connected to "+(host)+" on port "+str(port))
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
while True:
response = input("Send: ")
if response == "exit":
s.sendall(response.encode('utf-8'))
s.close()
There is nothing wrong with your code, but the LOGIC of it is wrong, in the Client.py
file and particularly in this loop: 您的代码没有任何问题,但是在
Client.py
文件中,尤其是在此循环中,其LOGIC错误:
while True:
response = input("Send: ")
if response == "exit":
s.sendall(response.encode('utf-8'))
This will not send to your Server
side anything but string exit
because of this: 由于以下原因,这不会将任何内容发送到
Server
端,而是字符串exit
:
if response == "exit":
So you are asking your Client.py
script to only send anything the user inputs matching the string exit
otherwise it will not send. 因此,您要让
Client.py
脚本仅发送与字符串exit
匹配的用户输入中的任何内容,否则它将不发送。
It will send anything at the beginning before this while
loop since you wrote: 自从您编写之后,它将在
while
循环之前的开始处发送任何内容:
initialMessage = input("Send: ")
s.sendall(initialMessage.encode('utf-8'))
But after you are inside that while
loop then you locked the s.sendall
to only send exit
string 但是在进入
while
循环之后,您将s.sendall
锁定为仅发送exit
字符串
You have to clean up your code logic. 您必须清理代码逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.