嘿,我对编程很新,做了一些c#,但对Python来说是全新的。 我已将我的覆盆子pi(python3)中的图像发送到我的笔记本电脑(c#)。我可以把字节发送但我不能打开图像,当它被接收(重新创建)? :(
顺便说一下这是我在stackoverflow上的第一篇文章,希望你能帮帮我:)。
C#代码(接收):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Drawing;
using System.IO;
namespace tmpRaspTcpServer
{
class Program
{
static void Main(string[] args)
{
IPAddress localAdd = IPAddress.Parse("xxx.xxx.xxx.xxx");
TcpListener listener = new TcpListener(IPAddress.Any, 8888);
Console.WriteLine("Listen...");
listener.Start();
while (true)
{
TcpClient client = listener.AcceptTcpClient();
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Reading bytes: " );
FileStream fs = new FileStream("c:\\tmp\\file.jpg", FileMode.Create);
TraditionalReceiveBinary(nwStream, fs);
}
}
private static void TraditionalReceiveBinary(NetworkStream nwstream, FileStream fs)
{
// read the file in chunks of 1KB
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = nwstream.Read(buffer, 0, buffer.Length)) > 0)
{
fs.Write(buffer, 0, bytesRead);
Console.Write("."); // a dot for each kb
}
fs.Flush();
}
}
}
Python3代码(发送):
import socket
HOST, PORT = "xxx.xxx.xxx.xxx", 8888
image = open('image.jpg', 'rb')
image_data = image.read()
image.close()
socketData = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socketData.connect((HOST,PORT))
socketData.sendall(image_data)
我没有收到任何错误,当我发送图片时,c#app在控制台中制作了点,但文件被损坏了#34;或者某事:(
我尝试过不同的编码和标题 - 但没有运气。
答案 0 :(得分:0)
您正在丢弃正在从套接字读取的第一个TcpClient.ReceiveBufferSize字节:
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
这会破坏您的输出文件。