2016-01-27 45 views
0

我想從一個asp.net網站發送消息到一個運行在覆盆子pi上的python文件。如果這是代碼上的蟒蛇上的piASP.NET和Python通信

import socket 

serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
serversocket.bind(('localhost', 8089)) 
serversocket.listen(5) # become a server socket, maximum 5 connections 

while True: 
    connection, address = serversocket.accept() 
    buf = connection.recv(64) 
    if len(buf) > 0: 
    print buf 
    break 

我只是需要一些幫助入門。假設我知道正在運行Python代碼的Raspberry Pi的外部和內部IP地址,我將如何開始使用ASP.NET的代碼?

我會用socket.io還是別的?在ASP.NET網站和Python之間進行通信的最佳想法或方法是什麼?我知道這個問題很普遍,但我需要一些幫助才能開始正確的方向。

+0

如果Python服務器直接在套接字上進行監聽(而不是使用某種協議,如HTTP或其他協議),那麼我想直接從.NET套接字連接就可以了。你試過了嗎? – David

+0

爲什麼使用套接字?試試'wsgiref',是非常基本的。 – dsgdfg

回答

0

(編輯)改進ASP.NET代碼:

protected void Page_Load(object sender, EventArgs e) 
{ 

    TcpClient client = new TcpClient("192.168.1.107", 8012); 

    // Translate the passed message into ASCII and store it as a Byte array. 
    Byte[] data = System.Text.Encoding.ASCII.GetBytes("Hello There"); 

    // Get a client stream for reading and writing. 
    // Stream stream = client.GetStream(); 

    NetworkStream stream = client.GetStream(); 

    // Send the message to the connected TcpServer. 
    stream.Write(data, 0, data.Length); 

    // Receive the TcpServer.response. 

    // Buffer to store the response bytes. 
    data = new Byte[256]; 

    // String to store the response ASCII representation. 
    String responseData = String.Empty; 

    // Read the first batch of the TcpServer response bytes. 
    Int32 bytes = stream.Read(data, 0, data.Length); 
    responseData = System.Text.Encoding.ASCII.GetString(data, 0, bytes); 
    Response.Write(responseData); 

    // Close everything. 
    stream.Close(); 
    client.Close(); 
    } 
} 

是工作,我在用的現在。有更好的選擇嗎?感謝您的回覆。 :)