【发布时间】:2023-12-31 09:48:01
【问题描述】:
我正在尝试将文件从 python 客户端发送到 c# 服务器,并通过先保存它然后在我的 MainWindow 上显示它来在屏幕上显示它。 我遇到了几个我不知道为什么会发生的问题(我是 C# 新手) 我遵循了本指南:http://snippetbank.blogspot.com/2014/04/csharp-client-server-file-transfer-example-1.html 问题是:
1.该文件未保存到我的文件夹中。
2。当我使用消息框尝试检测它是否传递了所有信息时,它看起来像是卡在了中间。
我已经坚持了很长一段时间,但无法弄清楚我错过了什么
Python 代码:
def send_file(conn, name):
try:
full_path = "Output/"+name
file_to_send = open(full_path, "rb")
size = os.path.getsize(full_path)
file_name = name + "\n"
size_to_send = str(size) + "\n"
conn.send(size_to_send.encode())
conn.send(file_name.encode())
while size > 0:
data = file_to_send.read(1024)
conn.send(data)
size -= len(data)
file_to_send.close()
return conn
except IOError:
print("FILE IS ALREADY OPEN")
C# 代码:
public static string ReceiveFile(StreamReader reader, TcpClient tcpClient)
{
string folder = @"C:\Users\Roy\Desktop\GUI243\GUI243\";
// The first message from the client is the file size
string cmdFileSize = reader.ReadLine();
MessageBox.Show(cmdFileSize);
// The first message from the client is the filename
string cmdFileName = reader.ReadLine();
MessageBox.Show(cmdFileName);
string full_path = folder + cmdFileName;
int length = Convert.ToInt32(cmdFileSize);
byte[] buffer = new byte[length];
int received = 0;
int read = 0;
int size = 1024;
int remaining = 0;
// Read bytes from the client using the length sent from the client
while (received < length)
{
remaining = length - received;
if (remaining < size)
{
size = remaining;
}
read = tcpClient.GetStream().Read(buffer, received, size);
if (read == 0)
{
break;
}
received += read;
}
// Save the file using the filename sent by the client
using (FileStream fStream = new FileStream(Path.GetFileName(cmdFileName), FileMode.Create))
{
fStream.Write(buffer, 0, buffer.Length);
fStream.Flush();
fStream.Close();
}
return full_path;
}
【问题讨论】:
-
MessageBox.Show(cmdFileName) - 消息框是否显示在该行上? StreamReader 的来源是什么?
-
@GiorgiChkhikvadze 是的,它确实显示以下行是: TcpClient tcpClient = tcpListener.AcceptTcpClient(); StreamReader reader = new StreamReader(tcpClient.GetStream());