我对Python开发还不熟悉,需要一些帮助。在
我有一个Raspberry Pi B+,我正计划用它作为家庭用品的控制器(比如在设定的时间打开一个泳池水泵)。我对C很熟悉,我想知道是否有一种方法可以编写一个在笔记本电脑上运行的C用户界面,并通过LAN将XML文件形式的数据发送给Raspberry Pi,告诉Pi该怎么做。我用C编写了一些代码,用Python编写了一些代码,试图发送和接收文件,但到目前为止,我的测试都没有成功。在
我在Raspberry Pi上有一些用Python编写的基本代码,用于控制一些GPIO管脚,我想知道这样的连接是否可行,是否也应该将Python代码重写成C。在
这是我的C#send file函数
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接收文件函数
^{pr2}$同样,到目前为止,我甚至无法在两个设备之间建立连接。我是否应该重新开始使用Pi并尝试使用C而不是Python?还是我错过了什么?我已经给这两个设备一个静态IP地址,并硬编码了两台机器上的IP地址。在
编辑: 这是我从C得到的控制台和stacktrace:
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).
我有两种方法可以从Windows PC访问我的Raspberry Pi。第一种是在PC上安装Putty connection manager之后,输入RPi IP地址会在PC上生成一个终端窗口,从中我可以执行RPi程序。在
在我的例子中,RPi连接到一个Windows工作组,映射为drive T:。我的C程序可以使用它在RPi上创建文件以进行写入或读取。在
尝试使用
强制Raspberry Pi侦听所有可用接口,因为
socket.gethostname()
可能不是您实际期望的接口。在更新:
试试这个在树莓派的一边:
^{pr2}$相关问题 更多 >
编程相关推荐