我正在学习服务器端和客户端连接:我正在尝试做的是在Qpython (android)上相互连接服务器端和客户端脚本
问题是当我运行它时,它给了我这个:
“ConnectionRefusedError:Errno [111] 连接被拒绝”
当我在我的计算机上运行相同的脚本时,它不会给我任何错误。
背景资料:
我在手机上使用 2 个不同的应用程序
和 1 在我的电脑上。
但我想这不是问题
客户
import socket
import sys
HOST, PORT = "localhost", 9999
Data = " ".join(sys.argv[1:]) + input(" Enter Message:\n"
# Create a socket (SOCK_STREAM means a TCP socket)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
# Connect to server and send data
sock.connect((HOST, PORT))
sock.sendall(bytes(data + "\n", "utf-8"))
# Receive data from the server and shut down
received = str(sock.recv(1024), "utf-8")
finally:
sock.close()
print("Sent: {}".format(data))
print("Received: {}".format(received))
服务器
import socketserver
class MyTCPHandler(socketserver.BaseRequestHandler):
def handle(self):
# self.request is the TCP socket connected to the client
self.data = self.request.recv(1024).strip()
print("{} wrote:".format(self.client_address[0]))
print(self.data)
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
# Create the server, binding to localhost on port 9999
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()