Help me out

G

Gohar

i have written the code to transfer image file through
sockets. Below is the code for client. It just runs and
exit nothing happens. Can anybody help?

In this code first i get the file size then the actual
file through bytes.

using System;
using System.Net.Sockets;
using System.IO;
using System.Threading;

namespace ImageClient
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class Class1
{
bool flag = true;
Socket clientSocket;
AsyncCallback pnfCallback = null;
int fileSize;
byte[] buffer = new byte[1024];
/// <summary>
/// The main entry point for the
application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
Class1 c = new Class1();
c.clientSocket = new Socket
(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType
..Tcp);
System.Net.IPEndPoint ipend = new
System.Net.IPEndPoint(System.Net.IPAddress.Parse(args
[0]),8221);
c.clientSocket.Connect(ipend);
c.WaitForData();

}
public void WaitForData()
{

if(pnfCallback == null)
{

pnfCallback = new
AsyncCallback(onDataReceived);
}

IAsyncResult result =
clientSocket.BeginReceive
(buffer,0,buffer.Length,SocketFlags.None,pnfCallback,null)
;

}
public void onDataReceived(IAsyncResult
result)
{

if(flag)
{
int count =
clientSocket.EndReceive(result);
char[] chars = new char
[count];

System.Text.Encoding.Default.GetDecoder().GetChars
(buffer,0,count,chars,0);
fileSize = int.Parse(new
string(chars));
Console.WriteLine("Got
the buffer " + fileSize);
Console.ReadLine();
flag=false;
buffer = null;
buffer = new byte
[fileSize];
WaitForData();
}
else
{

clientSocket.EndReceive
(result);
FileStream fs = new
FileStream("c:/def.gif",FileMode.Create);
fs.Write
(buffer,0,buffer.Length);
fs.Flush();
fs.Close();
WaitForData();
}

}
}
}
 
N

Nicholas Paldino [.NET/C# MVP]

Gohar,

This just exits because once you run the WaitForData method, this runs
asynchronously, and control returns to the thread and then it just exits,
and the program exits as well. You need to set up some sort of mechanism by
which the main thread of the program will wait until the file is downloaded.

Hope this helps.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top