PDA

View Full Version : سوال: ارسال نام و فرمت فایل در شبکه همراه با فایل



SardareEshgh
سه شنبه 02 آذر 1395, 11:26 صبح
دوستان سلام
طبق کد زیر از طرف سرور فایلی رو به سمت کلاینت میفرستم.
مشکل اینجاست که در طرف کلاینت ، فایل دریافت شده هیچ نام و فرمتی نداره.

سمت سرور :

public partial class Form1 : Form
{
int port = 1500;
string targetIP = "192.168.68.2";
TcpClient client;


public Form1()
{
InitializeComponent();

//pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
//pictureBox1.Image = Properties.Resources.loading;
}

private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
if (open.ShowDialog() == DialogResult.OK)
{
FileStream fs = new FileStream(open.FileName, FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, (Int32)fs.Length);

client = new TcpClient();
client.Connect(targetIP, port);

int bufferSize = client.ReceiveBufferSize;
int totalByteSend = 0;

NetworkStream ns = client.GetStream();

//pictureBox1.Visible = label1.Visible = true;

for (int i = 0; i <= fs.Length / bufferSize; i++)
{
if (fs.Length - (i * bufferSize) >= bufferSize)
{
ns.Write(data, i * bufferSize, bufferSize);
totalByteSend += bufferSize;
}
else
{
ns.Write(data, i * bufferSize, (int)fs.Length - (i * bufferSize));
totalByteSend += (int)fs.Length - (i * bufferSize);
}

}

// pictureBox1.Visible = label1.Visible = false;

MessageBox.Show("file sent" + " and total data sent is " + (float)((float)totalByteSend / 1048576));
}
}
}

سمت کلاینت :

public partial class Form1 : Form
{

int port = 1500;
TcpListener listener;
TcpClient client;
NetworkStream ns;
BackgroundWorker bgw;

public Form1()
{
InitializeComponent();

IPHostEntry ips = Dns.GetHostByName(Dns.GetHostName());
IPAddress localip = IPAddress.Parse(ips.AddressList[0].ToString());

listener = new TcpListener(localip, port);

bgw = new BackgroundWorker();
bgw.DoWork += new DoWorkEventHandler(bgw_DoWork);
}

void bgw_DoWork(object sender, DoWorkEventArgs e)
{
while (true)
{
listener.Start();
client = listener.AcceptTcpClient();
ns = client.GetStream();
byte[] reciver = new byte[client.ReceiveBufferSize];
FileStream fs = new FileStream(Application.StartupPath + "\\" + new Random().Next(2, 10000).ToString(), FileMode.Append, FileAccess.Write);

int bytesRead;
do
{
bytesRead = ns.Read(reciver, 0, client.ReceiveBufferSize);
fs.Write(reciver, 0, bytesRead);
}
while (bytesRead != 0);

fs.Close();
MessageBox.Show("file recived successfuly");
}
}

private void Form1_Load(object sender, EventArgs e)
{
bgw.RunWorkerAsync();
}
}

SardareEshgh
پنج شنبه 04 آذر 1395, 08:41 صبح
سلام
دوستان ممنون میشم راهنمایی کنید