472,805 Members | 1,791 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,805 software developers and data experts.

how to tranfer file using networkstream through sockets in c#..

hi,
plzz check my code and let me know where the problem is
lying...becuase whenever i try to tansfer the file of 573KB(mp3) it
just tranfer few Kb of file(Somtimes 5.2Kb,somtimes 32Kb..every time i
run the program).....but when i watch the transfering of bytes by
debuging it.(RED dot on while(nfs.CanRead) )..it shows that complete
bytes are transfered.(in my case i-e 573Kb)....i am unable to
understand whats going wrong in my program.
same is the problem with text file..it reads the bytes but not write
on file...

*CODE at RECIEVING END*
byte[] buffed = new byte[6000] ;
string Fname=System.Text.Encoding.ASCII.GetString(f_name,
0,count_char);
string pth=@"C:\Documents and Settings\Administrator\My Documents
\shared1\ ";
FileStream fout = new FileStream(pth+Fname, FileMode.Create,
FileAccess.Write) ;
NetworkStream nfs = new NetworkStream(Dsock) ;
string myCompleteMessage = "";
int numberOfBytesRead = 0;
while(nfs.CanRead)
{
if(nfs.DataAvailable)
{
numberOfBytesRead = nfs.Read(buffer, 0, buffer.Length);
myCompleteMessage =
string.Concat(System.Text.Encoding.ASCII.GetString (buffer, 0,
numberOfBytesRead));
fout.Write(buffer,0,(int)numberOfBytesRead) ;

}
}

*CODE at SENDING END*
int len=0;
byte[] buffed = new byte[6000] ;
//Open the file requested for download
FileStream fin = new FileStream(loadfile,FileMode.Open ,
FileAccess.Read) ;
//One way of transfer over sockets is Using a NetworkStream
NetworkStream nfs = new NetworkStream(DlSck_Arr[0]);
while(nfs.CanWrite)
{
//Read from the File (len contains the number of bytes read)
len =fin.Read(buffed,0,buffed.Length) ;
//Write the Bytes on the Socket
nfs.Write(buffed, 0,len);
//Increase the bytes Read counter
}
len=len+0;
}

Apr 21 '07 #1
3 10967
if you do async sockets, you can receive the entire file at once. this way
you wont have to fiddle with loops, a method will run when your receive
buffer is filled, or when an end of message is found. look at the BeginSend
and BeginReceive methods of a socket. if you need specific code, let me know
--
-iwdu15
Apr 22 '07 #2
On Apr 22, 7:20 am, iwdu15 <jmmgoalsteratyahoodotcomwrote:
if you do asyncsockets, you can receive the entirefileat once. this way
you wont have to fiddle with loops, a method will run when your receive
buffer is filled, or when an end of message is found. look at the BeginSend
and BeginReceive methods of a socket. if you need specific code, let me know
--
-iwdu15
hmmmm...i wud b greatful to u if u send me example code....thanks

Apr 23 '07 #3
heres a rough code example....should get u pointed in the right direction

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;

namespace SampleSocket
{
public class SampleSocket
{
//our socket
private Socket soc;

//our buffer to receive bytes
private Byte[] buffer;

//ascii encoding for converting bytes to stings, etc
private ASCIIEncoding ascii;
//AsyncCallBack objects for Async Socker usage
private AsyncCallback ConnectCallBack;
private AsyncCallback ReceiveCallBack;
private AsyncCallback SendCallBack;
public SampleSocket()
{

//create socket
soc = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);

//create a buffer of size 4095
buffer = new Byte[4095];

//create ascii encoding object
ascii = new ASCIIEncoding();

//create async objects to tell which method to go to when invoked
ConnectCallBack = new AsyncCallback(soc_ConnectCallBack);
ReceiveCallBack = new AsyncCallback(soc_ReceiveCallBack);
SendCallBack = new AsyncCallback(soc_SendCallBack);

}

public void Connect(String IP)
{

//parse IP
IPAddress ip = Dns.GetHostEntry(IP).AddressList[0];

//create IPEndPoint from ip and Port
IPEndPoint ep = new IPEndPoint(ip, 11000);

//begin connecting to other user
soc.BeginConnect(ep, ConnectCallBack, null);

}

private void soc_ConnectCallBack(IAsyncResult ar)
{

//finalize the connection and begin receiving information from
the user, passing in our AsyncCallBack object
soc.EndConnect(ar);
soc.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
ReceiveCallBack, null);

}

private void soc_ReceiveCallBack(IAsyncResult ar)
{

//get the number of bytes received
int numBytes = soc.EndReceive(ar);

//if numBytes < 1 then other user disconnected from session, so
shutdown socket and exit method
if (numBytes < 1)
{

soc.Shutdown(SocketShutdown.Both);

return;

}

//if buffer is null, exit method
if (buffer == null)
return;

//get string from bytes (can also write the bytes to a file, all
bytes received are in the array named buffer)
String str = ascii.GetString(buffer);

//clear the array so if the array isnt filled next time, we wont
have extra info
Array.Clear(buffer, 0, buffer.Length);

//begin received again
soc.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None,
ReceiveCallBack, null);

}

public void Send(Byte[] bt)
{

//begin sending to connected client, passing our AsyncDelegate
telling where to go when the send is complete
soc.BeginSend(bt, 0, bt.Length, SocketFlags.None, SendCallBack,
null);

}

private void soc_SendCallBack(IAsyncResult ar)
{

//handle send finalize here...
soc.EndSend(ar);

}

}
}
hope this helps

--
-iwdu15
Apr 23 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: cmjman | last post by:
I have an issue where networkStream.Write doesn't perform its write downstream from my client program until the network stream is closed. I then see the data that was sent appear on the other side....
1
by: Chin Fui | last post by:
I am now doing my final year project using VB.NET. The project is about implement a multiplayer network game. But now I am stuck in the connection part, no idea in how to start to write the network...
0
by: Henk | last post by:
Hi, I have a problem with sending a file. I have a client application that connects to a server and sends the string "data". Then it sends a file. If the server receives "data", the method...
1
by: crashed | last post by:
Hi, I am using C# in .NET 2.0 and im trying to read a stream from a socket. The code works on the first attempt but fails on subsequent attempts. It is in a multithreaded application. It seems...
4
by: DaveR | last post by:
I have a background thread to accept and process TCP/IP connections. When the application shuts down I want to gracefully terminate it. The thread will block in NetworkStream.Read() waiting for...
10
by: David | last post by:
I have googled to no avail on getting specifically what I'm looking for. I have found plenty of full blown apps that implement some type of file transfer but what I'm specifcally looking for is an...
3
by: prognoob | last post by:
I need help coding a file transfer in C#. It would be over TCP/IP using sockets... most of the solutions i have come across, they use networkstream and i have read online that there is no need to...
0
by: =?Utf-8?B?T2xpdmllciBHSUw=?= | last post by:
Hello, I try to post an HTTP message containing an XML document, and I get the following exception : System.Net.WebException: The underlying connection was closed: An unexpected error...
4
by: keithseah | last post by:
Hi all, i've been having this problem and its kiiling me! i'm a newbie at this so i hope someone would be able to help me. picture link:...
2
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 2 August 2023 starting at 18:00 UK time (6PM UTC+1) and finishing at about 19:15 (7.15PM) The start time is equivalent to 19:00 (7PM) in Central...
0
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
0
linyimin
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
0
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
0
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
14
DJRhino1175
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
0
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
0
by: lllomh | last post by:
How does React native implement an English player?
2
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.