我正在尝试通过套接字执行命令,但程序在一次输入后自行停止。我是套接字的新手,这就是我所做的一切。
客户端:
import socket
HOST = input("Enter the ip: ")
PORT = 7629
addr = (HOST, PORT)
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((addr))
#
while True:
msg = input("Enter command> ")
msg = str.encode(msg)
clientsocket.send(msg)
receivemsg = clientsocket.recv(1024).decode()
print(receivemsg)
#
服务器:
import socket
import os
import sys
host = '0.0.0.0'
port = 7629
size = 1024
addr = (host, port)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((addr))
s.listen(20)
while True:
print("Listening.")
client ,adress = s.accept()
data = client.recv(size)
print("received message: ", data.decode())
if data.decode() == "dir":
msg = "succesful!"
client.send(msg.encode())
答案 0 :(得分:0)
尝试将您的客户更改为:
import socket
HOST = input("Enter the ip: ")
PORT = 7629
addr = (HOST, PORT)
#clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#clientsocket.connect((addr))
while True:
msg = input("Enter command> ")
msg = str.encode(msg)
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((addr))
clientsocket.send(msg)
receivemsg = clientsocket.recv(1024).decode()
print(receivemsg)
clientsocket.close()
请注意服务器端的代码。如果发送的命令是“dir”,那么它将发回“成功”,否则您的客户端将不会收到任何消息,它将永远等待。