2016-01-27 40 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(); 
    } 
} 

是工作,我在用的现在。有更好的选择吗?感谢您的回复。 :)