473,800 Members | 2,332 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Remote control with TcpListener

Hi,

The app i develop supose to have a remote control/reporting feature,
so that if a client connects to it, he can obtain information about application state and to send some commands.

I started with using TcpListener in a separate thread of the app.
Something like this:

// =============== ============= CODE BEGIN =============== ========
public void ListenerThreadF unction()
{
RemServer = new TcpListener(IPA ddress.Parse("1 27.0.0.1"),9999 );
RemServer.Start ();

// Buffer for reading data
Byte[] bytes = new Byte[65535];
String data = null;

while(true)
{
// Get the client connection
TcpClient client = RemServer.Accep tTcpClient();
// Get the connection stream
NetworkStream stream = client.GetStrea m();
int i;
// Loop to get all the data client sent
while((i = stream.Read(byt es, 0, bytes.Length))! =0)
{
// Convert dada to string
data = System.Text.Enc oding.ASCII.Get String(bytes, 0, i);
data = data.ToUpper(). Trim();

// Now check what command arrived:

// Client asks to provide list of recorders
if (data == "GET_RECORDERS_ LIST")
{
// Form return string in format

}
}
client.Close();
}
}

// =============== ====== CODE END =============== =========

It's partially taken from a MSDN example.

The idea how i see it should be this: client connects, sends a request, listener responds, then client sends another request, server responds, and so on.

The first problem i see is that server will be blocked waiting for 65535 bytes of data from client in stream.Read()
Second, i'm not sure how i should correctly design the loops in the function.

Any ideas would be appreciated!

Thank you,
Andrey
Nov 16 '05 #1
2 7720
Hi,

Your server code blocks on the call to read 65535 bytes of data.
At some point in time, the client sends the server a request packet,
consisting
of 100 bytes (for example). On the server side, the call while((i =
stream.Read(byt es, 0, bytes.Length))! =0)
will then return (unblock) and i will equal 100. So that solves your
blocking problem.

Now, about parsing the command that the client has sent you. I would use
integers instead
of strings to represent the commands. Let us assume the client can send us 5
possible commands as follows:

1 = GET_RECORDERS_L IST
2 = GET_DRUMS_LIST
3 = GET_GUITARS_LIS T
4 = GET_FLUTES_LIST
5 = GET_SAXPHONES_L IST

I would first declare a delegate as follows: delegate int
ClientCmdHandle r();
Then I would declare an array of event handlers to hold my 5 commands, as
follows:

ClientCmdHandle r[] executeClientCm d = new ClientCmdHandle r[5];
executeClientCm d[0] = new ClientCmdHandle r(getRecordersL ist);
executeClientCm d[1] = new ClientCmdHandle r(getDrumsList) ;
executeClientCm d[2] = new ClientCmdHandle r(getGuitarsLis t);
executeClientCm d[3] = new ClientCmdHandle r(getFlutesList );
executeClientCm d[4] = new ClientCmdHandle r(getSaxphonesL ist);

then I would declare the following methods as follows

public int (getRecordersLi st) { do something useful here }
public int (getDrumsList) { do something useful here }
public int (getGuitarsList ) { do something useful here }
public int (getFlutesList) { do something useful here }
public int (getSaxphonesLi st) { do something useful here }

Once I have retrieved the cmd from the client packet, I would do as follows

if( (cmd > 0) && (cmd < 6) )
{
executeClientCm d[cmd - 1](); // this will call the corresponding
commands method
}

hope this helps
LK

even though you are blocking on the buffer size of 65536 bytes, the call
will return when fewer bytes are read
"MuZZy" <le*******@yaho o.com> wrote in message
news:I4******** ************@rc n.net...
Hi,

The app i develop supose to have a remote control/reporting feature,
so that if a client connects to it, he can obtain information about application state and to send some commands.
I started with using TcpListener in a separate thread of the app.
Something like this:

// =============== ============= CODE BEGIN =============== ========
public void ListenerThreadF unction()
{
RemServer = new TcpListener(IPA ddress.Parse("1 27.0.0.1"),9999 );
RemServer.Start ();

// Buffer for reading data
Byte[] bytes = new Byte[65535];
String data = null;

while(true)
{
// Get the client connection
TcpClient client = RemServer.Accep tTcpClient();
// Get the connection stream
NetworkStream stream = client.GetStrea m();
int i;
// Loop to get all the data client sent
while((i = stream.Read(byt es, 0, bytes.Length))! =0)
{
// Convert dada to string
data = System.Text.Enc oding.ASCII.Get String(bytes, 0, i);
data = data.ToUpper(). Trim();

// Now check what command arrived:

// Client asks to provide list of recorders
if (data == "GET_RECORDERS_ LIST")
{
// Form return string in format

}
}
client.Close();
}
}

// =============== ====== CODE END =============== =========

It's partially taken from a MSDN example.

The idea how i see it should be this: client connects, sends a request, listener responds, then client sends another request, server responds, and
so on.
The first problem i see is that server will be blocked waiting for 65535 bytes of data from client in stream.Read() Second, i'm not sure how i should correctly design the loops in the function.
Any ideas would be appreciated!

Thank you,
Andrey

Nov 16 '05 #2
Laxmikant Rashinkar wrote:
Hi,

Your server code blocks on the call to read 65535 bytes of data.
At some point in time, the client sends the server a request packet,
consisting
of 100 bytes (for example). On the server side, the call while((i =
stream.Read(byt es, 0, bytes.Length))! =0)
will then return (unblock) and i will equal 100. So that solves your
blocking problem.
Thank you for response!
Now i re-read the MSDN article and see that it says that if NO data is available it will block.
So it answers my question! Thanks a lot!

Now, about parsing the command that the client has sent you. I would use
integers instead
of strings to represent the commands. Let us assume the client can send us 5
possible commands as follows:

1 = GET_RECORDERS_L IST
2 = GET_DRUMS_LIST
3 = GET_GUITARS_LIS T
4 = GET_FLUTES_LIST
5 = GET_SAXPHONES_L IST

I would first declare a delegate as follows: delegate int
ClientCmdHandle r();
Then I would declare an array of event handlers to hold my 5 commands, as
follows:

ClientCmdHandle r[] executeClientCm d = new ClientCmdHandle r[5];
executeClientCm d[0] = new ClientCmdHandle r(getRecordersL ist);
executeClientCm d[1] = new ClientCmdHandle r(getDrumsList) ;
executeClientCm d[2] = new ClientCmdHandle r(getGuitarsLis t);
executeClientCm d[3] = new ClientCmdHandle r(getFlutesList );
executeClientCm d[4] = new ClientCmdHandle r(getSaxphonesL ist);

then I would declare the following methods as follows

public int (getRecordersLi st) { do something useful here }
public int (getDrumsList) { do something useful here }
public int (getGuitarsList ) { do something useful here }
public int (getFlutesList) { do something useful here }
public int (getSaxphonesLi st) { do something useful here }

Once I have retrieved the cmd from the client packet, I would do as follows

if( (cmd > 0) && (cmd < 6) )
{
executeClientCm d[cmd - 1](); // this will call the corresponding
commands method
}

hope this helps
LK

even though you are blocking on the buffer size of 65536 bytes, the call
will return when fewer bytes are read
"MuZZy" <le*******@yaho o.com> wrote in message
news:I4******** ************@rc n.net...
Hi,

The app i develop supose to have a remote control/reporting feature,
so that if a client connects to it, he can obtain information about


application state and to send some commands.
I started with using TcpListener in a separate thread of the app.
Something like this:

// =============== ============= CODE BEGIN =============== ========
public void ListenerThreadF unction()
{
RemServer = new TcpListener(IPA ddress.Parse("1 27.0.0.1"),9999 );
RemServer.Sta rt();

// Buffer for reading data
Byte[] bytes = new Byte[65535];
String data = null;

while(true)
{
// Get the client connection
TcpClient client = RemServer.Accep tTcpClient();
// Get the connection stream
NetworkStre am stream = client.GetStrea m();
int i;
// Loop to get all the data client sent
while((i = stream.Read(byt es, 0, bytes.Length))! =0)
{
// Convert dada to string
data = System.Text.Enc oding.ASCII.Get String(bytes, 0, i);
data = data.ToUpper(). Trim();

// Now check what command arrived:

// Client asks to provide list of recorders
if (data == "GET_RECORDERS_ LIST")
{
// Form return string in format

}
}
client.Close( );
}
}

// =============== ====== CODE END =============== =========

It's partially taken from a MSDN example.

The idea how i see it should be this: client connects, sends a request,


listener responds, then client sends another request, server responds, and
so on.
The first problem i see is that server will be blocked waiting for 65535


bytes of data from client in stream.Read()
Second, i'm not sure how i should correctly design the loops in the


function.
Any ideas would be appreciated!

Thank you,
Andrey


Nov 16 '05 #3

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

Similar topics

1
2213
by: Stephen Remde | last post by:
what the kosher way of vreating a tcp client/server app in .net? can anyone recommend a good in depth tutorial? currently im using a TcpListener but i cant get a remotre address from the TcpClient's it returns Stephen
1
1819
by: Doug Wyatt | last post by:
So I'll preface this with the fact that I'm a UNIX developer by training and have just recently gotten in to C# development on Windows. I'm basically running in to a problem whereby I suspect something to do with process groups or threads and closeOnExec semantics (to speak in POSIX terms) is causing me a problem. I've got a windows service (let's call it "myService") that, among other things, does : onStart creates a TcpListener on a...
1
3208
by: Ethan | last post by:
Hi, In quite a fix here. Hope someone can help ASAP. I need to get the IP address of the client that connects when I use TcpListener.AcceptTcpConnections. I know I can get the information using the socket class but I really need to know how to get this information using the TcpClient class. I tried writing a class from TcpCLient but then found out that I can not cast down the inheritance hierarchy, only up. Any help is greatly
4
4402
by: Rob White | last post by:
OK, so I have a TcpListener that is waiting for sockets, this piece of code: IPAddress localAddress = Dns.GetHostByName(Dns.GetHostName()).AddressList; IPEndPoint localEP = new IPEndPoint(localAddress, 9000); TcpListener tcpListen = new TcpListener(localEP); tcpListen.Start(); Socket skt = tcpListen.AcceptSocket(); .... do some socket stuff skt.Close();
1
2713
by: MuZZy | last post by:
HI, How do i get a remote TcpClient address here? // ======================================= TcpListener l = new TcpListener(IPAddress.Parse("127.0.0.1"), 8080); TcpListener.Start(); While (true) {
0
1404
by: Mark | last post by:
Ok, Why is this so hard too do? I have a TCPListener that's working exactly as expected. It fires off a new thread to listen on calling this function. ======================================================================== Private Sub DoListen() m_oListener.Start() While True
3
4375
by: Bjørn Eliasen | last post by:
Hi, I have an application running on all pc's in our company. Basically it is a TCPListener awaiting for sockets to connect and on connection performs the required tasks. The app works fine, but while the listener is awaiting for socket to connect several other applications can't start, and even installation of new applications migth hang. In order to finalise the other apps or installations the tcp listener is killed resulting in the other...
3
1964
by: Wayne And Miles | last post by:
I have created a server application that listens for connections using the TCPListener class. When I connect to the server using a client on the same machine as the server, all works as expected. However, when I attempt to connect to the server application from a client on a remote machine on my LAN, the connection is refused. I have used Ethereal to confirm that the request from the client is being received on the server machine. I...
1
8641
by: Darwin | last post by:
Setting a server to listen on 8080 for incoming connections. Written in VS2005 on a Multi-homed machine. I get the warning: Warning 1 'System.Net.Sockets.TcpListener.TcpListener(int)' is obsolete: 'This method has been deprecated. Please use TcpListener(IPAddress localaddr, int port) instead. on the code: TcpListener tcpListener = new TcpListener(8080); Do I really have to specify every IP address that I want to listen on?
0
9551
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
10505
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...
0
10276
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10253
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
7580
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
6813
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
5606
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4149
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
3
2945
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.