By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
445,931 Members | 1,567 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 445,931 IT Pros & Developers. It's quick & easy.

Problems sending and receiving files

P: n/a
Lee
Hi,

I am trying to send and receive a file (it is actually an xml file, however
any file may possibly be sent) using;-

sending .....

public void send()
{

byte[] data = new byte[1024];
string input, stringData;
TcpClient client;
try
{
client = new TcpClient(server, 9050);
}
catch (SocketException)
{
Console.WriteLine("Unable to connect to server");
return;
}

NetworkStream ns = client.GetStream();
int recv = ns.Read(data, 0, data.Length);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);

input = "STOR";
ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
ns.Flush();

data = new byte[1024];
recv = ns.Read(data, 0, data.Length);
stringData = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(stringData);

FileInfo finfo = new FileInfo(theFile);
input = finfo.Length.ToString();
Console.WriteLine(input);
ns.Write(Encoding.ASCII.GetBytes(input), 0, input.Length);
ns.Flush();

FileStream fs = new FileStream(theFile, FileMode.Open);
BinaryReader r = new BinaryReader(fs, Encoding.UTF8);

long len = finfo.Length;
int bytesSent = 0;
fs.Position = 0;

while (len > 0)
{
data = new byte[1024];

bytesSent = r.Read(data, 0, data.Length);
ns.Write(data, 0, bytesSent);
ns.Flush();

len = len - bytesSent;
}

Console.WriteLine("Disconnecting from server...");
ns.Close();
client.Close();

}
and receiving using ...

(have not put in all the preamble, code up to here works fine)

public void receive()
{
string welcome = null;
long length;
string clientdata = null;
int bytesRead = 0;
byte[] bytes = new byte[1024];

welcome="SENDLENTH";
bytes = Encoding.ASCII.GetBytes(welcome);
ns.Write(bytes, 0, welcome.Length);
ns.Flush();
bytes = new byte[1024];
bytesRead = ns.Read(bytes, 0, bytes.Length);
clientdata = Encoding.ASCII.GetString(bytes, 0, bytesRead);
Console.WriteLine(clientdata);
length = long.Parse(clientdata);

welcome = "SEND";
bytes = Encoding.ASCII.GetBytes(welcome);
ns.Write(bytes, 0, welcome.Length);
ns.Flush();
while (length > 0)
{
bytes = new byte[1024];
bytesRead = ns.Read(bytes, 0, bytes.Length);
clientdata = clientdata + Encoding.UTF8.GetString(bytes, 0,
bytesRead);
length = length-bytesRead;
}

Console.WriteLine(clientdata);
}

end of code

now when i recieve a small xml file it always has a few random chars (3 in
fact) as a preamble to it, also if i try sending a big file it seems to send
ok, but the server hangs (and or kicks up errors).

am i missing something obvious?

TIA
May 23 '06 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.