通过C语言向/从Python发送/接收文件

时间:2015-04-11 18:48:34

标签: c# python sockets raspberry-pi lan

我对Python开发很新,需要一些帮助。

我有Raspberry Pi B+,我打算将它用作家用物品的控制器(例如在设定的时间开启泳池泵)。我对C#非常熟悉,并且想知道是否有办法编写C#用户界面以在笔记本电脑上运行,并通过LAN将XML文件形式的数据发送到Raspberry Pi,告诉Pi该做什么。我在C#中编写了一些代码,在Python中编写了一些代码来尝试发送和接收文件,但到目前为止我的测试都没有成功。

我在Raspberry Pi上用Python编写了一些用于控制某些GPIO引脚的基本代码,并且想知道如果我将Python代码重写为C#,这样的连接是否可行。

这是我的C#发送文件功能

public void SendFile(string fileName)
{
    try
    {
        string IpAddressString = piIP;
        IPEndPoint ipEnd_client = new IPEndPoint(IPAddress.Parse(IpAddressString), portnumber);
        Socket clientSock_client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);

        string filePath = "";

        fileName = fileName.Replace("\\", "/");
        Console.WriteLine(fileName);

        while (fileName.IndexOf("/") > -1)
        {
            filePath += fileName.Substring(0, fileName.IndexOf("/") + 1);
            fileName = fileName.Substring(fileName.IndexOf("/") + 1);
        }

        byte[] fileNameByte = Encoding.UTF8.GetBytes(fileName);
        if (fileNameByte.Length > 5000 * 1024)
        {
            Console.WriteLine("File size is more than 5Mb, please try with small file.");
            return;
        }

        Console.WriteLine("Buffering ...");
        string fullPath = filePath + fileName;

        byte[] fileData = File.ReadAllBytes(fullPath);
        byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
        byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);


        fileNameLen.CopyTo(clientData, 0);
        fileNameByte.CopyTo(clientData, 4);
        fileData.CopyTo(clientData, 4 + fileNameByte.Length);

        Console.WriteLine("Connection to server...");
        clientSock_client.Connect(ipEnd_client);

        Console.WriteLine("File sending...");
        clientSock_client.Send(clientData, 0, clientData.Length, 0);

        Console.WriteLine("Disconnecting...");
        clientSock_client.Close();
        Console.WriteLine("File [" + fullPath + "] transferred.");
    }
    catch (Exception ex)
    {
        if (ex.Message == "No connection could be made because the target machine actively refused it")
            Console.WriteLine("File Sending fail. Because server not running.");
        else
            Console.WriteLine("File Sending fail. " + ex.Message);
        return;
    }
    connected = true;
    return;
}

这是我的Python接收文件功能

import socket
import sys
s = socket.socket()
s.bind((socket.gethostname(), 8080))
s.listen(3)

while True:

    #Accept connections from the outside
    (clientsocket, address) = s.accept()
    print(address)
    i = 1
    f = open('file_' + str(i) + ".xml", 'wb')
    i = i + 1
    while True:
        l = clientsocket.recv(1024)
        while l:
            f.write(1)
            l.clientsocket.recv(1024)
    f.close()

    sc.close()

s.close()

同样,到目前为止,我甚至无法在两个设备之间建立连接。我应该重新开始使用P#而不是Python吗?或者我错过了什么?我已经为这两台设备提供了静态IP地址,并且现在在两台机器上硬编码了IP地址。

编辑: 这是我从C#获得的控制台和堆栈跟踪:

Buffering ...
Connection to server...
A first chance exception of type 'System.Net.Sockets.SocketException' occurred in System.dll
File Sending fail. No connection could be made because the target machine actively refused it 10.51.21.199:8080
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Connect(EndPoint remoteEP)
at App1.Stuffs.SendFile(String fileName) in
...Projects\App1\App1\Stuffs.cs:line 308
The thread '<No Name>' (0x1684) has exited with code 0 (0x0).

2 个答案:

答案 0 :(得分:1)

尝试使用

s.bind(('', 8080))

强制Raspberry Pi监听所有可用接口,因为socket.gethostname()可能不是您实际期望的接口。

<强>更新

在Raspberry Pi端试试这个:

import socket
import sys
s = socket.socket()
s.bind(('', 8080))
s.listen(3)

i = 0

while True:

    #Accept connections from the outside
    (clientsocket, address) = s.accept()
    print(address)
    i = i + 1
    with open('file_' + str(i) + ".xml", 'wb') as f:
        while True:
            l = clientsocket.recv(1024)
            if not l:
                break
            f.write(l)

    clientsocket.close()

s.close()

答案 1 :(得分:0)

我有两种方法可以从Windows PC访问我的Raspberry Pi。第一个是在PC上安装Putty连接管理器之后,输入RPi IP地址会在PC上生成一个终端窗口,从那里我可以执行RPi程序。

在我的案例中,RPi连接到Windows工作组,映射为驱动器T:。我的C程序可以使用它在RPi上创建文件进行写入或阅读。