使用网络流的同步逻辑
我正在使用网络流发送文件名(例如:“text.txt”),然后发送文件。服务器应该读取名称并创建一个写入流来写入数据。服务器在读取命令中从文件中获取名称+数据以仅获取名称的问题。我认为这还不清楚。 问题我从文件中获取文件名+一些数据。 发送文件名然后发送文件数据的代码:
ASCIIEncoding asci = new ASCIIEncoding();
TcpClient clientSocket = new TcpClient(textBox2.Text, 8880);
NetworkStream networkStream = clientSocket.GetStream();
byte[] b = asci.GetBytes(s);//s is the name of the file
networkStream.Write(b, 0, b.Length);
networkStream.Flush();
while(true)
{
file = fileStream.Read(fileBuffer,0,fileBuffer.Length);
networkStream.Write(fileBuffer,0,file);
if(file == 0) break;
}
服务器接收的代码。名称和数据,
byte [] buffer2 = new byte[1];
String filename = "";
ASCIIEncoding asci = new ASCIIEncoding();
while (true)
{
int k = networkStream.Read(buffer2, 0, buffer2.Length);
filename = filename+asci.GetString(buffer2, 0, k);
if (k == 0) break;
}
using (Stream fileStream = File.OpenWrite("C:/Users/Laptop/Documents/" + filename))
{
while (true)
{
thisRead = networkStream.Read(dataByte, 0, blockSize);
fileStream.Write(dataByte, 0, thisRead);
if (thisRead == 0) break;
}
谢谢。我想我不知道如何说或说明这个问题。
I am using network stream to send a file name (example :"text.txt") and then send the file. the server is supposed to read the name and create a write stream to write the data in. the problem that the server gets the name + data from the file in the read command to get the name only. i think this is unclear.
the question i get the file name + some data from the file.
code that sends file name then file data:
ASCIIEncoding asci = new ASCIIEncoding();
TcpClient clientSocket = new TcpClient(textBox2.Text, 8880);
NetworkStream networkStream = clientSocket.GetStream();
byte[] b = asci.GetBytes(s);//s is the name of the file
networkStream.Write(b, 0, b.Length);
networkStream.Flush();
while(true)
{
file = fileStream.Read(fileBuffer,0,fileBuffer.Length);
networkStream.Write(fileBuffer,0,file);
if(file == 0) break;
}
the code that the server rec. the name and data with
byte [] buffer2 = new byte[1];
String filename = "";
ASCIIEncoding asci = new ASCIIEncoding();
while (true)
{
int k = networkStream.Read(buffer2, 0, buffer2.Length);
filename = filename+asci.GetString(buffer2, 0, k);
if (k == 0) break;
}
using (Stream fileStream = File.OpenWrite("C:/Users/Laptop/Documents/" + filename))
{
while (true)
{
thisRead = networkStream.Read(dataByte, 0, blockSize);
fileStream.Write(dataByte, 0, thisRead);
if (thisRead == 0) break;
}
thanks. i think i dont know how to say or illustrate the problem.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须发送一些指示文件名结尾的内容。只要未接收到这个或这些停止字符,服务器就会接收文件名,然后接收有效负载。
例如,HTTP 使用
\r\n\r\n
来标记 HTTP 标头的结束。You have to send something that indicates the end of the filename. The server receives the filename as long as this or these stop characters are not received and it receives the payload afterwards.
For example, HTTP uses
\r\n\r\n
to mark the end of the HTTP header.