473,386 Members | 2,129 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

NetworkStream tcp error

I am trying to us a simple NetworkStream to transfer a file over tcp. This
works most of the time, but one specific file never downloads(.mdb file). It
seems to close the socket and I get an "unable to write data to transport
connection" error. I have tried multiple ways to transfer this
file(including remoting, sockets without network stream) and downloaded
different examples of client/server byte transfer, all with the same result.
The file downloads around 705kb and stops. File size seems to have nothing
to do with it. The really strange thing is that if I reverse the bytes and
then send the file, it works, but the db is almost always corrupt on the
other side.

Here is the client:

using System;
using System.Diagnostics;
using System.Runtime.Remoting;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.IO;
namespace C4I.FileTransfer
{
/// <summary>
/// Summary description for FileTransferClient.
/// </summary>
public class FileTransferClient
{
private int _instanceNumber;
private Socket clientSocket;
private bool _isReceiving = false;
public bool isReceiving{get{return _isReceiving;}}
private string _ipAddress;
private int _port;
public FileTransferClient(int instanceNumber, string ipAddress, int port)
{
_instanceNumber = instanceNumber;
_ipAddress = ipAddress;
_port = port;
}

int _fileLength;
string _fileName;
Thread receiveThread;
public void ReceiveFile(string fileName, int fileLength)
{
_fileName = fileName;
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
//clientSocket.SetSocketOption(SocketOptionLevel.Soc ket,
SocketOptionName.ReuseAddress, 1);
IPHostEntry IPHost = Dns.Resolve(_ipAddress);
IPEndPoint endPoint = new IPEndPoint(IPHost.AddressList[0], _port);
clientSocket.Connect(endPoint);
receiveThread = new Thread(new ThreadStart(ReceiveFile));
receiveThread.Name = "Receive Thread";
_fileLength = fileLength;
receiveThread.Start();
}
private void ReceiveFile()
{
try
{
FileStream fs = null;
try
{
if (!File.Exists(_fileName))
fs = File.Create(_fileName);
else
fs = new FileStream(_fileName, FileMode.Create, FileAccess.ReadWrite);
int count = 0;
NetworkStream nfs = new NetworkStream(clientSocket);
while (count < _fileLength)
{
byte[] buffer = new byte[1024];
_isReceiving = true;
int i = nfs.Read(buffer, 0 , buffer.Length);
fs.Write(buffer, 0, (int)i);
count = count + i;
}
_isReceiving = false;
fs.Close();
}
catch (Exception exc)
{
Trace.WriteLine(exc.Message);
try
{
_isReceiving = false;
fs.Close();
}
catch{}
}
}
catch (Exception exc)
{
Trace.WriteLine(exc.Message);
_isReceiving = false;
}
}

}

and here is the server
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Net.Sockets;
using System.Net;
using System.Threading;
namespace C4I.FileTransfer
{
/// <summary>
/// Summary description for FileTransferServer.
/// </summary>
public class FileTransferServer
{
Socket _serverSocket;
Socket _clientSocket;
Thread listenThread;
string _ipAddress;
int _port;
public FileTransferServer(string ipAddress, int port)
{
_ipAddress = ipAddress;
_port = port;
listenThread =new Thread(new ThreadStart(ListenForClients));
listenThread.Name = "File Transfer listen thread";
listenThread.Start();
}

public void ListenForClients()
{
_serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
IPHostEntry IPHost = Dns.Resolve(_ipAddress);
IPEndPoint endPoint = new IPEndPoint(IPHost.AddressList[0], _port);
_serverSocket.Blocking = true;
_serverSocket.Bind(endPoint);
_serverSocket.Listen(-1);
try
{
_clientSocket = _serverSocket.Accept();
}
catch{}
}
NetworkStream ns = null;
public void SendFile(string fileName)
{
if (_clientSocket == null || !_clientSocket.Connected)
{
End(false);
ListenForClients();
}
Thread.Sleep(1000);
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[1024];
ns = new NetworkStream(_clientSocket);
int count = 0;
int length = (int)fs.Length;
try
{
while (count < length && ns.CanWrite)
{
int bytesRead = fs.Read(buffer, 0, buffer.Length);
ns.Write(buffer, 0, bytesRead);
count += bytesRead;
}
}
catch
{
End(false);
ListenForClients();
}
finally
{
try
{
fs.Close();
}
catch{}
}
}
public void End(bool withDispose)
{
try{ns.Close();}
catch{}
try{_clientSocket.Shutdown(SocketShutdown.Both);}
catch{}
try{_clientSocket.Close();}
catch{}
try{_serverSocket.Close();}
catch{}
if (withDispose)
this.Dispose();

}
public void Dispose()
{
if (this.listenThread != null)
{
try
{
_serverSocket.Close();
}
catch{}
try
{
this.listenThread.Interrupt();
this.listenThread.Abort();
}
catch{}
this.listenThread = null;
}
}
}
}
Nov 17 '05 #1
1 2606

It turns out that the database I was trying to send had large amounts of
empty bytes in the file. As soon as I zipped the file and sent it,
everything was fine.
Nov 17 '05 #2

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: Daniel | last post by:
i would like to konw when the data sent so that i can close the streamwriter and networkstream is there some sort of call backs/events i have to implement for this to work? if so how? can i just...
7
by: Dustin B | last post by:
Since this issue encompasses so many things - I have to generally post it I guess. I'm building an application for a Wireless PDA - when it is connected to the Network I tested a TCPListener &...
4
by: 0to60 | last post by:
I have a class that wraps a TcpClient object and manages all the async reading of the socket. It works really nice, and I use it all over the place. But there's this ONE INSTANCE where I create...
2
by: Srinivas R. Loka | last post by:
I have a TCP server to which a number of mobile devices connect. If a device disconnects(mostly no clean close as they usually lose cell coverage or shutdown), and the server then tries to send...
4
by: Kai Thorsrud | last post by:
Hi! How do i check: if "NetworkStream.Null = true then" it says .Null does not supports type Boolean Thanks /Kai
0
by: Al Wilkerson | last post by:
Hey, Has anyone ever got a "Unable to read data from transport connected" message after reading data from a streamreader composed of a networkstream. For example: Server TcpListener...
7
by: littleIO | last post by:
Hi, I'm stuck on a very simple problem and just cant seem to get around it, little help would be much appreciated. I have a server which listens, receives calls, processes them and sends back the...
1
by: Almund | last post by:
Hi, I'm trying to implement streaming over http and got stuck with a problem trying to send chunks of data using the .Net NetworkStream object. All works fine as long as I send the entire data in...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

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.