簡體   English   中英

無法將消息從python服務器發送到Java客戶端

[英]Can't send message from python server to java client

我嘗試通過本地網絡在Raspberry Pi(Python中的服務器)和Java客戶端之間創建客戶端/服務器應用程序。

我不知道如何將消息從Python服務器發送到Java客戶端。 我總是遇到錯誤:[Errno 32]管道損壞。

我看不到我錯了。

這里的服務器代碼:

class ServerLED():
'''
classdocs
'''


def __init__(self, port = 15555):
    '''
    Constructor
    '''
    self.socketPi = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.socketPi.bind(("", port))
    self.response = ""

def listening(self):
    self.socketPi.listen(5)
    self.client, self.address = self.socketPi.accept()
    print "{} connected".format( self.address )

def receivingMessage(self):
    self.response = self.client.recv(1024)
    if self.response != "":
            print self.response

def answer(self):
    messageTosend = "Echo \r\n"
    try:
        self.socketPi.send(messageTosend)
    except socket.error, e:
        print "error is ", e
        self.socketPi.close()

我以這種方式使用該功能:

socketPi = Server.ServerLED()
print "listening..."
socketPi.listening()
print "sending message..."
socketPi.answer()
print "done"
socketPi.receivingMessage()

在客戶端(在JAVA中):

Socket socket = new Socket("192.168.1.18", 15555);
System.out.println("SOCKET = " + socket);

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
str = in.readLine();      // Reding "ECHO"

System.out.println(str);     

out.println("Hello");          // sending message

我總是卡在服務器的第一個“ send()”中。 如果我首先從客戶端向服務器發送消息,則服務器會讀取該消息,但無法響應。

服務器輸出:

Start python for LED
listening...
('192.168.1.13', 58774) connected
sending message...
error is  [Errno 32] Broken pipe

有人知道我錯了嗎? 非常感謝。

馬克西姆

通常這是一個奇怪的設置,但是在服務器中,您應該在連接套接字(self.client)上發送,而不是在偵聽套接字(self.socketPi)上發送。

一個問題是,您在Java中創建的Socket未bind ,即-只是創建了Socket對象,但未打開以等待樹莓派傳入的Socket連接。

添加行

socket.bind(new java.net.InetSocketAddress("192.168.1.18", 15555));

創建套接字后。 Socket構造函數中的地址可能不是必需的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM