473,703 Members | 2,598 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Can someone help me

Chi
what is the "unable to write data to the transport connection"
I use the oreilly , programming c#

using System;
using System.Net.Sock ets;
using System.Text;
using System.IO;
// get a file name from the client
// open the file and send the
// contents from the server to the client
public class AsynchNetworkFi leServer
{
class ClientHandler
{
// constructor
public ClientHandler(
Socket socketForClient )
{
// initialize member variable
socket = socketForClient ;
// initialize buffer to hold
// contents of file

buffer = new byte[BufferSize];
// create the network stream
networkStream =
new NetworkStream(s ocketForClient) ;
// set the file callback for reading
// the file
myFileCallBack =
new AsyncCallback(t his.OnFileCompl etedRead);
// set the callback for reading from the
// network stream
callbackRead =
new AsyncCallback(t his.OnReadCompl ete);
// set the callback for writing to the
// network stream
callbackWrite =
new AsyncCallback(t his.OnWriteComp lete);
inputStream= null;

}
// begin reading the string from the client
public void StartRead( )
{
// read from the network
// get a filename
networkStream.B eginRead(
buffer, 0, buffer.Length,
callbackRead, null);
}
// when called back by the read, display the string
// and echo it back to the client
private void OnReadComplete( IAsyncResult ar )
{
int bytesRead = networkStream.E ndRead(ar);
// if you got a string
if( bytesRead > 0 )
{
// turn the string to a file name
string fileName =
System.Text.Enc oding.ASCII.Get String(
buffer, 0, bytesRead);
// update the console
Console.Write(
"Opening file {0}", fileName);
// open the file input stream
if(inputStream! =null)
{
inputStream =
File.OpenRead(f ileName);
}
else
{
inputStream= new FileStream(file Name,FileMode.O pen);
}
// begin reading the file
inputStream.Beg inRead(
buffer, // holds the results
0, // offset
buffer.Length, // BufferSize
myFileCallBack, // call back delegate
null); // local state object

}
else
{
Console.WriteLi ne( "Read connection dropped");
networkStream.C lose( );
socket.Close( );
networkStream = null;
socket = null;
}
}
// when you have a buffer-full of the file
void OnFileCompleted Read(IAsyncResu lt asyncResult)
{
int bytesRead =
inputStream.End Read(asyncResul t);
// if you read some file
try
{
if (bytesRead > 0)
{
// write it out to the client
networkStream.B eginWrite(
buffer, 0, bytesRead, callbackWrite, null);
}
}
catch(Exception e)
{
//Have problem in here
Console.WriteLi ne(e.Message);
}
}
// after writing the string, get more of the file
private void OnWriteComplete ( IAsyncResult ar )
{
networkStream.E ndWrite(ar);
Console.WriteLi ne( "Write complete");
// begin reading more of the file
inputStream.Beg inRead(
buffer, // holds the results
0, // offset
buffer.Length, // (BufferSize)
myFileCallBack, // call back delegate
null); // local state object
}
private const int BufferSize = 2048;
private byte[] buffer;
private Socket socket;
private NetworkStream networkStream;
private FileStream inputStream;
private AsyncCallback callbackRead;
private AsyncCallback callbackWrite;
private AsyncCallback myFileCallBack;
}
public static void Main( )
{
AsynchNetworkFi leServer app =
new AsynchNetworkFi leServer( );

app.Run( );
}
private void Run( )
{
// create a new TcpListener and start it up
// listening on port 65000
TcpListener tcpListener = new TcpListener(650 00);
tcpListener.Sta rt( );
// keep listening until you send the file
for (;;)
{
// if a client connects, accept the connection
// and return a new socket named socketForClient
// while tcpListener keeps listening
Socket socketForClient =
tcpListener.Acc eptSocket( );
if (socketForClien t.Connected)
{
Console.WriteLi ne("Client connected");
ClientHandler handler =
new ClientHandler(s ocketForClient) ;
handler.StartRe ad( );
}
}
}
}
Jan 26 '06 #1
3 2728
Chi wrote:
what is the "unable to write data to the transport connection"
That's hard to say with no information about where you're getting it,
or under what situation.
I use the oreilly , programming c#


So was this code taken directly from the book, or is that just what
you're learning from?

One thing which concerns me is that your OnReadComplete assumes that
whenever you've successfully read a piece of data, that it must contain
a complete filename. What happens if a long filename is sent which is
split over multiple packets, for instance?

Treat it as a stream of data, with no end other than when the
connection is dropped. If you need to signal one piece of data, either
have something saying when it's ended, or specify to start with how
long that piece of data is.

Jon

Jan 26 '06 #2
Chi
Thx first,
the code is base on the book but i change a little bit, the example from

the book is only support text file, but i want to also support binary file.
actually, i am new to c#, and i haven't many programming experience
One thing which concerns me is that your OnReadComplete assumes that
whenever you've successfully read a piece of data, that it must contain
a complete filename. What happens if a long filename is sent which is
split over multiple packets, for instance


How can i handle this problem? I am sorry about my English is not very
good,and Tnank again
the origianl code is below

using System;
using System.Net.Sock ets;
using System.Text;
using System.IO;
// get a file name from the client
// open the file and send the
// contents from the server to the client
public class AsynchNetworkFi leServer
{
class ClientHandler
{
// constructor
public ClientHandler(
Socket socketForClient )
{
// initialize member variable
socket = socketForClient ;
// initialize buffer to hold
// contents of file

buffer = new byte[256];
// create the network stream
networkStream =
new NetworkStream(s ocketForClient) ;
// set the file callback for reading
// the file
myFileCallBack =
new AsyncCallback(t his.OnFileCompl etedRead);
// set the callback for reading from the
// network stream
callbackRead =
new AsyncCallback(t his.OnReadCompl ete);
// set the callback for writing to the
// network stream
callbackWrite =
new AsyncCallback(t his.OnWriteComp lete);
}
// begin reading the string from the client
public void StartRead( )
{
// read from the network
// get a filename
networkStream.B eginRead(
buffer, 0, buffer.Length,
callbackRead, null);
}
// when called back by the read, display the string
// and echo it back to the client
private void OnReadComplete( IAsyncResult ar )
{
int bytesRead = networkStream.E ndRead(ar);
// if you got a string
if( bytesRead > 0 )
{
// turn the string to a file name
string fileName =
System.Text.Enc oding.ASCII.Get String(
buffer, 0, bytesRead);
// update the console
Console.Write(
"Opening file {0}", fileName);
// open the file input stream
inputStream =
File.OpenRead(f ileName);
// begin reading the file
inputStream.Beg inRead(
buffer, // holds the results
0, // offset
buffer.Length, // BufferSize
myFileCallBack, // call back delegate
null); // local state object

}
else
{
Console.WriteLi ne( "Read connection dropped");
networkStream.C lose( );
socket.Close( );
networkStream = null;
socket = null;
}
}
// when you have a buffer-full of the file
void OnFileCompleted Read(IAsyncResu lt asyncResult)
{
int bytesRead =
inputStream.End Read(asyncResul t);
// if you read some file
if (bytesRead > 0)
{
// write it out to the client
networkStream.B eginWrite(
buffer, 0, bytesRead, callbackWrite, null);
}
}
// after writing the string, get more of the file
private void OnWriteComplete ( IAsyncResult ar )
{
networkStream.E ndWrite(ar);
Console.WriteLi ne( "Write complete");
// begin reading more of the file
inputStream.Beg inRead(
buffer, // holds the results
0, // offset
buffer.Length, // (BufferSize)
myFileCallBack, // call back delegate
null); // local state object
}
private const int BufferSize = 256;
private byte[] buffer;
private Socket socket;
private NetworkStream networkStream;
private Stream inputStream;
private AsyncCallback callbackRead;
private AsyncCallback callbackWrite;
private AsyncCallback myFileCallBack;
}
public static void Main( )
{
AsynchNetworkFi leServer app =
new AsynchNetworkFi leServer( );

app.Run( );
}
private void Run( )
{
// create a new TcpListener and start it up
// listening on port 65000
TcpListener tcpListener = new TcpListener(650 00);
tcpListener.Sta rt( );
// keep listening until you send the file
for (;;)
{
// if a client connects, accept the connection
// and return a new socket named socketForClient
// while tcpListener keeps listening
Socket socketForClient =
tcpListener.Acc eptSocket( );
if (socketForClien t.Connected)
{
Console.WriteLi ne("Client connected");
ClientHandler handler =
new ClientHandler(s ocketForClient) ;
handler.StartRe ad( );
}
}
}
}
Jan 26 '06 #3
Chi wrote:
the code is base on the book but i change a little bit, the example from
the book is only support text file, but i want to also support binary file.
actually, i am new to c#, and i haven't many programming experience


Right - in that case, I would back off from asynchronous IO for a
while. Work out your protocol, then write a synchronous version (using
Stream.Read rather than Stream.BeginRea d) and then convert it to use
asynchronous IO if necessary.
One thing which concerns me is that your OnReadComplete assumes that
whenever you've successfully read a piece of data, that it must contain
a complete filename. What happens if a long filename is sent which is
split over multiple packets, for instance


How can i handle this problem? I am sorry about my English is not very
good,and Tnank again


You need to work out what your protocol is - what the client will send,
how you'll respond etc. Consider the fact that as you're really dealing
with streams of data, if the client sends over "SomeFilena me" you might
see that all in one go, or as "So" followed by "meFile" followed by
"name".

Jon

Jan 26 '06 #4

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

Similar topics

2
1847
by: Sean | last post by:
I have two sites that i use for personal stuff (family, friends, photos). They are PHP sites butim not a programmer. They were setup by a friend who no longer helps with them. There are some things with the Gallery upload and topics that just don't work anymore. I suspect it would be trivial for someone who knows PHP to fix. I am willing to pay $100 a year for someone to keep the sites up and running...minimal time is needed. ...
114
7713
by: muldoon | last post by:
Americans consider having a "British accent" a sign of sophistication and high intelligence. Many companies hire salespersons from Britain to represent their products,etc. Question: When the British hear an "American accent," does it sound unsophisticated and dumb? Be blunt. We Americans need to know. Should we try to change the way we speak? Are there certain words that sound particularly goofy? Please help us with your advice on this...
1
1545
by: Janne Naukkarinen | last post by:
Have someone commercial Digital Mars (DMC) IDDE? I need help making makefiles, it is easier with IDDE. However, IDDE is not freely distributed on net. There is current WinVN WIP:
5
2443
by: Raziq Shekha | last post by:
Hello all, Is there a way to figure out when was the last time someone connected to a database? SQL 2000 environment. Thanks, Raziq.
3
1583
by: MarcJessome | last post by:
Hi, I was wondering if someone could help me through learning C++. I've tried learning before, but I find I would work better if I had someone that could help explain a few things to me. Im using Bruce Eckel's Thinking in C++, but I have used others before. I use msn, icq and aim if its possible for someone to help me on an instant messenger. Thanks, Marc
1
1288
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ - How do I direct someone to this FAQ? ----------------------------------------------------------------------- This document is posted to clj very frequently. There should be no reason to direct someone to it. However, if someone asks a question answered in this FAQ or in one of the resources listed herein, please let them know their question is answered in the...
13
2061
by: FAQ server | last post by:
----------------------------------------------------------------------- FAQ Topic - How do I direct someone to this FAQ? ----------------------------------------------------------------------- This document is posted to clj very frequently. There should be no reason to direct someone to it. However, if someone asks a question answered in this FAQ or in one of the resources listed herein, please let them know their question is answered...
7
3131
by: Ross Culver | last post by:
I need to ensure that session variables are removed whenever someone leaves my web site. My understanding is that this should be happening automatically with the session mode set to InProc. But it's not. Every machine I'm testing this on does the same thing, but then again, everyone is using Internet Explorer 7.0 with multiple tabs active. Also, this problem just popped up, probably due to a change I've made, but I don't have a clue...
11
1791
by: Adrian | last post by:
Could someone please translate the code below into C#? Please also tell me the libraries I might need. Many thanks, Adrian. int main() { (GetProcAddress( LoadLibrary( "krnl386.exe" ), "exitkernel" ))();
1
1288
by: Apolakkiatis | last post by:
I was experimenting around and tried to make it so that if someone presses the F key on their keyboard it also sends the rest of the letters to complete F*** anytime someone presses that letter... I know it's cruel but I just want to mess around with my friend and send it to him, hahaha... I know that the 32 to 128 is wrong, but I dont know what the # for F is.... It's probably more messed up than just that so someone please help me! Public...
0
8667
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9251
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9014
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6585
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5922
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4429
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3122
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.