turning sockets off

G

Guest

I'm have an app the opens a socket and I want the socket to stay open till
the user clicks a button. I pass a string of "m_start" to start a listener,
and "m_end" to the function listen_func to stop the code. The problem is when
I try to compile the code I receive the error, "The type or namespace name
'myListener' could not be found." The code is as follows,

public void listen_func(string m_s)
{
if (m_s=="m_start")
{

Encoding ASCII = Encoding.ASCII;

// Create a listener on port 8227
System.Net.Sockets.TcpListener myListener = new
System.Net.Sockets.TcpListener(8227);

myListener.Start();
// Program blocks on Accept() until a client connects
Socket mySocket = myListener.AcceptSocket();
Byte[] RecvBytes = new Byte[256];
Int32 bytes = mySocket.Receive(RecvBytes, RecvBytes.Length, 0);
string s = ASCII.GetString(RecvBytes, 0, bytes);

{
DateTime now = DateTime.Now;
String strDateLine = now.ToShortDateString() + " " + now.ToLongTimeString();
Byte[] byteDateLine =
System.Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
mySocket.Send(byteDateLine,byteDateLine.Length,0);
}

}
else{

myListener.Stop();
}

How do I reference the myListener.Stop() in the else of the if statement to
avoid the error?
 
S

Sean Hederman

Move it to be an instance variable of your class:
class MyClass {
System.Net.Sockets.TcpListener myListener = null;

public void listen_func(string m_s) {
....
}
}

Just make sure you test it against null before calling Stop on it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top