[英]File sending from server to one client or multiple in C#
這是我的服務器端應用程序代碼:有一個邏輯錯誤沒有得到解決請任何人 hlp .....
public void SendFile(string IP, string path, string FileName) { try {
FileStream fs = new FileStream(path, FileMode.Open);//assign file to stream
byte[] buffer = new byte[fs.Length];//initialize buffer with stream length
int len = (int)fs.Length;
fs.Read(buffer, 0, len);//read bytes from stream
fs.Close();
BinaryFormatter br = new BinaryFormatter();
TcpClient myclient = new TcpClient(IP, 9000);
NetworkStream myns = myclient.GetStream();//assign stream to client
br.Serialize(myns, FileName);//provide header to stream
BinaryWriter mysw = new BinaryWriter(myns);
mysw.Write(buffer);//write file in stream
MessageBox.Show("File Successfully Transfered", "File Send", MessageBoxButtons.OK, MessageBoxIcon.Information);
mysw.Close();
myns.Close();
myclient.Close();
}
catch
{
MessageBox.Show("Reciever end Not Found", "File Sending Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
這是我的客戶端應用程序代碼,有一個邏輯錯誤沒有得到解決請任何人 hlp .....
公共無效文件接收器(){
NetworkStream myns;
TcpListener mytcpfilelistner;
Socket mysocketfile;
Thread myth;
BinaryReader bb;
try
{
mytcpfilelistner = new TcpListener(9000);
mytcpfilelistner.Start();
mysocketfile = mytcpfilelistner.AcceptSocket();
myns = new NetworkStream(mysocketfile);
BinaryFormatter br = new BinaryFormatter();
object op;
op = br.Deserialize(myns); // Deserialize the Object from Stream
bb = new BinaryReader(myns);
byte[] buffer = bb.ReadBytes(2000000);
FileStream fss = new FileStream("C:\\" + (string)op, FileMode.CreateNew, FileAccess.Write);
fss.Write(buffer, 0, buffer.Length);
fss.Close();
mytcpfilelistner.Stop();
MessageBox.Show("One File Reeceived and Saved in C Drive", "File Recieve", MessageBoxButtons.OK, MessageBoxIcon.Information);
LB.Client.lbclient objlb = new LB.Client.lbclient();
objlb.popup("One File Recieved and And Seved in C:\\" + (string)op);
if (mysocketfile.Connected == true)
{
while (true)
{
FileReceiver();
}
}
}
catch
{ }
}
我不明白你上面的問題是什么。 但是,您可以查看此線程SendFile over TCP/IP .NET CF ,以了解通過套接字發送文件的更簡單方法。 此外,我真的建議您閱讀並使用 C# 和 IDisposable 中的 using 語句,因為您應該在上面的代碼中使用它來確定性地清理代碼分配的資源。 這是一篇讓您入門的文章https://msdn.microsoft.com/en-us/library/yh598w02.aspx
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.