我已经为此工作了两天,我无法弄明白。 我想通过TCP传输文件(服务器发送,客户端接收)。
我面临的问题是我想为接收方实现一种方法,以便知道它所获得的文件的文件名是什么。 到目前为止我的工作代码
public void SendFile(string path, string IP) { TcpClient client = new TcpClient(); client.Connect(IP, 1095); using (NetworkStream networkStream = client.GetStream()) using (FileStream fileStream = File.OpenRead(path)) { ASCIIEncoding asci = new ASCIIEncoding(); byte[] b = asci.GetBytes(path); networkStream.Write(b, 0, b.Length); networkStream.Flush(); fileStream.CopyTo(networkStream); } client.Close(); } private void ListenForFile() { TcpListener listener = new TcpListener(IPAddress.Any, 1095); listener.Start(); using (TcpClient incoming = listener.AcceptTcpClient()) using (NetworkStream networkStream = incoming.GetStream()) using (FileStream fileStream = File.OpenWrite(@pathName + @"\something.extension")) { networkStream.CopyTo(fileStream); } listener.Stop(); }I have been working on this for two days and I can't figure it out. I want to transfer a file over TCP (server sending, client receiving).
The problem that I'm facing is I want to implement a way for the receiving side to know what the file name is of the file it is getting. Working code I have thus far
public void SendFile(string path, string IP) { TcpClient client = new TcpClient(); client.Connect(IP, 1095); using (NetworkStream networkStream = client.GetStream()) using (FileStream fileStream = File.OpenRead(path)) { ASCIIEncoding asci = new ASCIIEncoding(); byte[] b = asci.GetBytes(path); networkStream.Write(b, 0, b.Length); networkStream.Flush(); fileStream.CopyTo(networkStream); } client.Close(); } private void ListenForFile() { TcpListener listener = new TcpListener(IPAddress.Any, 1095); listener.Start(); using (TcpClient incoming = listener.AcceptTcpClient()) using (NetworkStream networkStream = incoming.GetStream()) using (FileStream fileStream = File.OpenWrite(@pathName + @"\something.extension")) { networkStream.CopyTo(fileStream); } listener.Stop(); }最满意答案
NetworkStream没有文件概念,它只是流式字节缓冲区的一个类。 您需要做的是提出某种形式的协议来将文件名发送到客户端。
您可以通过首先传输文件名和文件名的长度,然后传输文件大小,然后传输实际的文件内容来完成此操作。
客户端可以读取文件名长度,读入文件名,读入文件大小然后读入文件数据。
NetworkStream has no concept of files it's just a class for streaming byte buffers. What you will have to do is come up with some form of protocol to send the filename to the client.
You could do this by transmitting the length of the filename and filename first followed by the file size and then transmit the actual file contents.
The client side can read in the filename length, read in the filename, read in the file size then read in the file data.
更多推荐
networkStream,client,fileStream,listener,电脑培训,计算机培训,IT培训"/> <meta
发布评论