I am making a program in 2 parts.
Part 1: C# server-socket Application running on PC, listening for commands, and acts accordingly.
Part 2: Java client-socket application running on phone, that sends a command to the pc, when a button is pressed.
Currently, i can send commands from the client to the server, and its all good.
But my problem is this: When i send a specific command to the server, i want the server to reply to the client, and the client to read that reply.
Thing just is, when the client tries to read, it time-outs.
Java client program:
class ClientThread implements Runnable
{
public void run()
{
try
{
Socket socket = new Socket(serverIpAddress, serverPort);
socket.setSoTimeout(5000);
while (true)
{
try
{
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
Log.d("Nicklas", "Out it goes");
out.println(Command);
if (Command == "CMD:GetOptions<EOF>")
{
Log.d("Nicklas", "Getting options");
try
{
Log.d("Nicklas", "Line 1");
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
Log.d("Nicklas", "Line 2");
String answer = in.readLine();
Log.d("Nicklas", "answer = " + answer );
}
catch (Exception ee)
{
Log.d("Nicklasasasas", ee.toString());
}
}
break;
}
catch (Exception e)
{
Log.d("Nicklas", "CAE = " + e.toString());
break;
}
}
socket.close();
}
catch (ConnectException ee)
{
Log.d("Nicklas", "Kunne ikke forbinde");
}
catch (Exception e)
{
Log.d("Nicklasssssss", e.toString());
}
}
}
This is called with:
Thread cThread = new Thread(new ClientThread());
cThread.start();
And uses the global variable "Command", which will contain different information, depending on what button was pressed.
The program fails on the line "String answer = in.readline();" with the exception "java.net.SocketTimeoutException".
This is the C# Server part of the program:
private void ListenForClients()
{
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication
//with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
//System.Diagnostics.Debug.WriteLine(encoder.GetString(message, 0, bytesRead));
string Input = (encoder.GetString(message, 0, bytesRead));
Input = Input.Trim();
object[] obj = new object[1];
obj[0] = Input;
if (Input == "CMD:GetOptions<EOF>")
{
try
{
byte[] buffer = encoder.GetBytes("CMD:Accepted");
clientStream.Write(buffer, 0, buffer.Length);
clientStream.Flush();
MessageBox.Show("Client program asked for reply");
}
catch (Exception e)
{
MessageBox.Show("Oh it no work!: " + e.ToString());
}
}
else
{
Udfor(Input);
}
}
tcpClient.Close();
}
Called with the following, in the Form1()
this.tcpListener = new TcpListener(IPAddress.Any, 4532);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
The C# Server seems to work fine, and does show the messagebox "client program asked for reply"
Anyone who can spot the error?
I figured it out!
The problem was the C#. When the server sent back the command "CMD:Accepted", it never closed the socket, so the android application had no idea of telling if it was done reading! Closing the socket right after flushing + of course not closing it again if i already did, did the trick!
Related
i have a problem i am unable to resolve as my c# knowledge is not very good.
I found some code on the internet and modified it according to my needs.
My problem is that when i send messages to clients only one receives the message, then the next message is received by another client and so on.
I want to send same message to all connected clients without losing any data.
Server
using System;
using System.Net.Sockets;
using System.Threading;
public class AsynchIOServer
{
static TcpListener tcpListener = new TcpListener(10);
static void Listeners()
{
Socket socketForClient = tcpListener.AcceptSocket();
if (socketForClient.Connected)
{
Console.WriteLine("Client:"+socketForClient.RemoteEndPoint+" now connected to server.");
NetworkStream networkStream = new NetworkStream(socketForClient);
System.IO.StreamWriter streamWriter =
new System.IO.StreamWriter(networkStream);
System.IO.StreamReader streamReader =
new System.IO.StreamReader(networkStream);
////here we send message to client
while (true){
Console.WriteLine("type your message to be recieved by client:");
string theString = Console.ReadLine();
streamWriter.WriteLine(theString);
////Console.WriteLine(theString);
streamWriter.Flush();
}
streamReader.Close();
networkStream.Close();
streamWriter.Close();
}
socketForClient.Close();
Console.WriteLine("Press any key to exit from server program");
Console.ReadKey();
}
public static void Main()
{
//TcpListener tcpListener = new TcpListener(10);
tcpListener.Start();
Console.WriteLine("************This is Server program************");
Console.WriteLine("Hoe many clients are going to connect to this server?:");
int numberOfClientsYouNeedToConnect =int.Parse( Console.ReadLine());
for (int i = 0; i < numberOfClientsYouNeedToConnect; i++)
{
Thread newThread = new Thread(new ThreadStart(Listeners));
newThread.Start();
}
}
}
Client:
using System;
using System.Net.Sockets;
using System.Threading;
public class Client
{
static public void Main(string[] Args)
{
TcpClient socketForServer;
try
{
socketForServer = new TcpClient("localHost", 10);
}
catch
{
Console.WriteLine(
"Failed to connect to server at {0}:999", "localhost");
return;
}
NetworkStream networkStream = socketForServer.GetStream();
System.IO.StreamReader streamReader =
new System.IO.StreamReader(networkStream);
System.IO.StreamWriter streamWriter =
new System.IO.StreamWriter(networkStream);
Console.WriteLine("*******This is client program who is connected to localhost on port No:10*****");
try
{
string outputString;
// read the data from the host and display it
{
while (true)
{
outputString = streamReader.ReadLine();
Console.WriteLine("Message Recieved by server:" + outputString);
streamWriter.Flush();
}
}
}
catch
{
Console.WriteLine("Exception reading from Server");
}
// tidy up
networkStream.Close();
Console.WriteLine("Press any key to exit from client program");
Console.ReadKey();
}
private static string GetData()
{
//Ack from sql server
return "ack";
}
}
Thank you
simple working multi-threaded server:
static void Process(Socket client) {
Console.WriteLine("Incoming connection from " + client.RemoteEndPoint);
const int maxMessageSize = 1024;
byte[] response;
int received;
while (true) {
// Send message to the client:
Console.Write("Server: ");
client.Send(Encoding.ASCII.GetBytes(Console.ReadLine()));
Console.WriteLine();
// Receive message from the server:
response = new byte[maxMessageSize];
received = client.Receive(response);
if (received == 0) {
Console.WriteLine("Client closed connection!");
return;
}
List<byte> respBytesList = new List<byte>(response);
respBytesList.RemoveRange(received, maxMessageSize - received); // truncate zero end
Console.WriteLine("Client (" + client.RemoteEndPoint + "+: " + Encoding.ASCII.GetString(respBytesList.ToArray()));
}
}
static void Main(string[] args) {
int backlog = -1, port = 2222;
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.ReceiveTimeout = -1;
// Start listening.
try {
server.Bind(new IPEndPoint(IPAddress.Any, port));
server.Listen(backlog);
}
catch (Exception) {
Console.WriteLine("Listening failed!");
Console.ReadKey();
return;
}
Console.WriteLine("Start listening...");
while(true) {
Socket client = server.Accept();
new System.Threading.Thread(() => {
try { Process(client); } catch (Exception ex) { Console.WriteLine("Client connection processing error: " + ex.Message); }
}).Start();
}
//Console.WriteLine("Press any key for exit...");
//Console.ReadKey();
}
And client:
static void WorkWithServer(Socket server) {
const int maxMessageSize = 1024;
byte[] response;
int received;
while(true) {
try {
// Receive message from the server:
response = new byte[maxMessageSize];
received = server.Receive(response);
if (received == 0) {
Console.WriteLine("Server closed connection.");
return;
}
List<byte> respBytesList = new List<byte>(response);
respBytesList.RemoveRange(received, maxMessageSize - received); // truncate zero end
Console.WriteLine("Server: " + Encoding.ASCII.GetString(respBytesList.ToArray()));
// Send message to the server:
Console.Write("You: ");
server.Send(Encoding.ASCII.GetBytes(Console.ReadLine()));
Console.WriteLine();
}
catch (Exception ex) {
Console.WriteLine("Error: " + ex.Message);
return;
}
}
}
static void Main(string[] args) {
IPEndPoint serverEp = new IPEndPoint(IPAddress.Parse("192.168.1.2"), 2222);
Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
server.ReceiveTimeout = -1;
// Connect to the server.
try { server.Connect(serverEp); }
catch (Exception) {
Console.WriteLine("Establish connection with server (" + serverEp + ") failed!");
Console.ReadKey();
return;
}
Console.WriteLine("Connection with server (" + serverEp + ") established!");
WorkWithServer(server);
Console.WriteLine("Press any key for exit...");
Console.ReadKey();
}
Edit as you need.
Your code is wrong.
First of all I'll give you some insight of how it's wrong and why it's not working the way you want.
You're creating n number of threads, and making them ALL wait for a connection. What if you exhaust the number of threads? What if any of them exits unexpectedly?
You are also sending the data wrong. By using Console.ReadLine you aren't passing the data through multiple threads and reading the line in each one, instead, the first one that calls Console.ReadLine will be the one that's going to receive it. This means you'll only be sending to only one Socket.
It's not ideal how you're managing this. There are dozens if not hundreds of multithreaded socket server/client available online, and I'd invite you to research a little bit more. But first I'd like you to research more about Thread/Task in C#.
My socket server is pretty simple so far:
public static void listen()
{
TcpListener server = null;
IPAddress address = IPAddress.Parse("127.0.0.1");
try
{
server = TcpListener.Create(5683);
server.Start();
}
catch (Exception e)
{
Console.WriteLine(e.StackTrace);
}
while (true)
{
Thread.Sleep(10);
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Accepted Client");
Thread thread = new Thread (new ParameterizedThreadStart(SwordsServer.ClientHandler));
thread.IsBackground = true;
thread.Start(client);
}
}
public static void ClientHandler(object c)
{
TcpClient client = (TcpClient)c;
NetworkStream netstream = client.GetStream();
bool connected = true;
while (connected)
{
Thread.Sleep(10);
try
{
byte[] bytes = new byte[client.ReceiveBufferSize];
netstream.Read(bytes, 0, bytes.Length);
Console.WriteLine("got data");
netstream.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
connected = false;
Console.WriteLine(e);
Console.WriteLine(e.StackTrace);
}
}
}
My question is, on a conceptual level, how would you keep tabs on each unique client and send updates from other threads to specific clients?
For example, if I have data for a specific client, how do I reach out to that client instead of broadcasting it? Or, if a client is no longer connected, how could I tell?
Thanks in advance for any assistance!
Your implementation for accepting multiple connections creates anonymous clients, meaning after more than 1 connection you wont be able to identify the right client. If identifying is the problem then you can do one thing, have the client send an identifier to the server like "Client1". Create a Dictionary and in your method ClientHandler(), read the identifier from client and add the TCPClient's object in the dictionary.
So the modified code would be something like this:
Dictionary<string, TCPClient> dictionary = new Dictionary<string, TCPClient>();
public static void ClientHandler(object c)
{
TcpClient client = (TcpClient)c;
NetworkStream netstream = client.GetStream();
bool connected = true;
while (connected)
{
Thread.Sleep(10);
try
{
byte[] bytes = new byte[client.ReceiveBufferSize];
//read the identifier from client
netstream.Read(bytes, 0, bytes.Length);
String id = System.Text.Encoding.UTF8.GetString(bytes);
//add the entry in the dictionary
dictionary.Add(id, client);
Console.WriteLine("got data");
netstream.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
connected = false;
Console.WriteLine(e);
Console.WriteLine(e.StackTrace);
}
}
}
Do note: Your application should be intelligent enough to dynamically decide on to which client the updates should be sent.
I'm trying to make a server client using a local console server on my pc and a client on windows phone 8.1. The problem that I have is that I don't know how to read the incoming data from the client. I've searched the internet and read serveral microsoft tutorials but they do not explain how to read the incoming data in the server. Here's what I have.
Client on windows phone 8.1:
private async void tryConnect()
{
if (connected)
{
StatusLabel.Text = "Already connected";
return;
}
try
{
// serverHostnameString = "127.0.0.1"
// serverPort = "1330"
StatusLabel.Text = "Trying to connect ...";
serverHost = new HostName(serverHostnameString);
// Try to connect to the
await clientSocket.ConnectAsync(serverHost, serverPort);
connected = true;
StatusLabel.Text = "Connection established" + Environment.NewLine;
}
catch (Exception exception)
{
// If this is an unknown status,
// it means that the error is fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
StatusLabel.Text = "Connect failed with error: " + exception.Message;
// Could retry the connection, but for this simple example
// just close the socket.
closing = true;
// the Close method is mapped to the C# Dispose
clientSocket.Dispose();
clientSocket = null;
}
}
private async void sendData(string data)
{
if (!connected)
{
StatusLabel.Text = "Must be connected to send!";
return;
}
UInt32 len = 0; // Gets the UTF-8 string length.
try
{
StatusLabel.Text = "Trying to send data ...";
// add a newline to the text to send
string sendData = "jo";
DataWriter writer = new DataWriter(clientSocket.OutputStream);
len = writer.MeasureString(sendData); // Gets the UTF-8 string length.
// Call StoreAsync method to store the data to a backing stream
await writer.StoreAsync();
StatusLabel.Text = "Data was sent" + Environment.NewLine;
// detach the stream and close it
writer.DetachStream();
writer.Dispose();
}
catch (Exception exception)
{
// If this is an unknown status,
// it means that the error is fatal and retry will likely fail.
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
StatusLabel.Text = "Send data or receive failed with error: " + exception.Message;
// Could retry the connection, but for this simple example
// just close the socket.
closing = true;
clientSocket.Dispose();
clientSocket = null;
connected = false;
}
}
(from http://msdn.microsoft.com/en-us/library/windows/apps/xaml/jj150599.aspx)
And the server:
public class Server
{
private TcpClient incomingClient;
public Server()
{
TcpListener listener = new TcpListener(IPAddress.Parse("127.0.0.1"), 1330);
listener.Start();
Console.WriteLine("Waiting for connection...");
while (true)
{
//AcceptTcpClient waits for a connection from the client
incomingClient = listener.AcceptTcpClient();
//start a new thread to handle this connection so we can go back to waiting for another client
Thread thread = new Thread(HandleClientThread);
thread.IsBackground = true;
thread.Start(incomingClient);
}
}
private void HandleClientThread(object obj)
{
TcpClient client = obj as TcpClient;
Console.WriteLine("Connection found!");
while (true)
{
//how to read and send data back?
}
}
}
It comes to the point where the server prints 'Connection found!', but I don't know how to go further.
Any help is appreciated!
EDIT:
Now my handleclientthread method looks like this:
private void HandleClientThread(object obj)
{
TcpClient client = obj as TcpClient;
netStream = client.GetStream();
byte[] rcvBuffer = new byte[500]; // Receive buffer
int bytesRcvd; // Received byte count
int totalBytesEchoed = 0;
Console.WriteLine("Connection found!");
while (true)
{
while ((bytesRcvd = netStream.Read(rcvBuffer, 0, rcvBuffer.Length)) > 0)
{
netStream.Write(rcvBuffer, 0, bytesRcvd);
totalBytesEchoed += bytesRcvd;
}
Console.WriteLine(totalBytesEchoed);
}
}
But it still doesn't write the bytes to the console
So... after a lot of searching the internet I have found a solution...
Server: to read from the server and send data back to the phone:
// method in a new thread, for each connection
private void HandleClientThread(object obj)
{
TcpClient client = obj as TcpClient;
netStream = client.GetStream();
Console.WriteLine("Connection found!");
while (true)
{
// read data
byte[] buffer = new byte[1024];
int totalRead = 0;
do
{
int read = client.GetStream().Read(buffer, totalRead, buffer.Length - totalRead);
totalRead += read;
} while (client.GetStream().DataAvailable);
string received = Encoding.ASCII.GetString(buffer, 0, totalRead);
Console.WriteLine("\nResponse from client: {0}", received);
// do some actions
byte[] bytes = Encoding.ASCII.GetBytes(received);
// send data back
client.GetStream().WriteAsync(bytes, 0, bytes.Length);
}
}
Phone(client): to send messages from the phone and read the messages from server:
private async void sendData(string dataToSend)
// import for AsBuffer(): using System.Runtime.InteropServices.WindowsRuntime;
{
if (!connected)
{
StatusLabel.Text = "Status: Must be connected to send!";
return;
}
try
{
byte[] data = GetBytes(dataToSend);
IBuffer buffer = data.AsBuffer();
StatusLabel.Text = "Status: Trying to send data ...";
await clientSocket.OutputStream.WriteAsync(buffer);
StatusLabel.Text = "Status: Data was sent" + Environment.NewLine;
}
catch (Exception exception)
{
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
StatusLabel.Text = "Status: Send data or receive failed with error: " + exception.Message;
closing = true;
clientSocket.Dispose();
clientSocket = null;
connected = false;
}
readData();
}
private async void readData()
{
StatusLabel.Text = "Trying to receive data ...";
try
{
IBuffer buffer = new byte[1024].AsBuffer();
await clientSocket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial);
byte[] result = buffer.ToArray();
StatusLabel.Text = GetString(result);
}
catch (Exception exception)
{
if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown)
{
throw;
}
StatusLabel.Text = "Receive failed with error: " + exception.Message;
closing = true;
clientSocket.Dispose();
clientSocket = null;
connected = false;
}
}
The 'await clientSocket.InputStream.ReadAsync(buffer, buffer.Capacity, InputStreamOptions.Partial)' command in the readData method was very unclear for me. I didn't know you had to make a new buffer, and the ReadAsync-method fills it(as i inderstand it). Found it here: StreamSocket.InputStreamOptions.ReadAsync hangs when using Wait()
I want to send a message from a C# application to the Android emulator or device over TCP. I have searched on Google and got the maximum results for Android client and C# server but not what I want to acheive.
Here is what I have tried; maybe I am going about it the wrong way but what I want is to send a message over TCP to an Android device.
Server Code to send a message:
private static int port = 4444;
private static TcpListener listener;
private static Thread thread;
private static int clientId = 0;
listener = new TcpListener(new IPAddress(new byte[] { 127, 0, 0, 1 }), port);
thread = new Thread(new ThreadStart(Listen));
thread.Start();
private static void Listen()
{
listener.Start();
MessageBox.Show("Listening on: " + port.ToString());
while (true)
{
MessageBox.Show("Waiting for connection....");
MessageBox.Show("Client No: " + clientId);
TcpClient client = listener.AcceptTcpClient();
Thread listenThread = new Thread(new ParameterizedThreadStart(ListenThread));
listenThread.Start(client);
}
}
private static void ListenThread(Object client)
{
NetworkStream netstream = ((TcpClient)client).GetStream();
MessageBox.Show("Request made");
clientId = clientId + 1;
// String message = "Hello world";
byte[] resMessage = Encoding.ASCII.GetBytes(clientId.ToString());
netstream.Write(resMessage, 0, resMessage.Length);
netstream.Close();
}
Client Code
private TextView textDisplay;
Socket socket;
private static final int TCP_SERVER_PORT = 4444;
ServerSocket ss = null;
try {
ss = new ServerSocket(TCP_SERVER_PORT);
//ss.setSoTimeout(10000);
//accept connections
Socket s = ss.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
//receive a message
String incomingMsg = in.readLine() + System.getProperty("line.separator");
Log.d("TcpServer", "received: " + incomingMsg);
textDisplay.append("received: " + incomingMsg);
//send a message
String outgoingMsg = "goodbye from port " + TCP_SERVER_PORT + System.getProperty("line.separator");
out.write(outgoingMsg);
out.flush();
Log.d("TcpServer", "sent: " + outgoingMsg);
textDisplay.append("sent: " + outgoingMsg);
//SystemClock.sleep(5000);
s.close();
} catch (InterruptedIOException e) {
//if timeout occurs
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ss != null) {
try {
ss.close();
} catch (IOException e) {
Log.d("Error",e.toString());
}
}
}
The problem lies in your Client code.
A socket is opened between two parties, one that plays the role of the listener / server that does bind->listen->accept and a client that connect
In your code there are two problems:
Your client should connect and not accept
Both your client and your server will try to read from the socket and write afterwards. There would be no problem if your read and write operations from the socket were on different threads.In your case this will result in a deadlock.
If you want both operations to be done on the same thread , sequentially then your client and server should perform the read and write in opposite order :
Client : read -> write
Server: write-> read
I have make an application to communicate with an IP Camera. That is configured to make connection on a predefined address. And TCP Listener is running on that address and accepts connection from camera. When camera connects i send command to get MJpeg stream from camera and camera starts sending stream in response to command.
I am using asynchronous method to read stream from socket. But after sometime my application is stuck while reading data from network stream.
I am using this code to read Data from network stream and i have write some messages on the screen to get status of camera connection.
private void ReadData()
{
try
{
string msg = "Reading Data... client connected " + _camClient.Connected.ToString() +
"... netStream Readable " +
_netStream.CanRead.ToString();
Console.WriteLine(msg);
_callback = new AsyncCallback(GetData);
_buffer = new byte[Buffersize];
_async = _netStream.BeginRead(_buffer, 0, Buffersize, _callback, null);
}
catch (Exception ex) { Console.WriteLine("ReadData: " + ex.Message); }
}
private void GetData(IAsyncResult result)
{
try
{
int read = _netStream.EndRead(result);
if (read > 0)
{
_data = new byte[read];
Array.Copy(_buffer, 0, _data, 0, read);
ProcessData();
}
ReadData();
}
catch (Exception ex) { Console.WriteLine("GetData: " + ex.Message); }
}
Firstly asynchronous methods on network streams are well known for loosing data or for never returning data!
In your case it could be the ProcessData call is blocking.
What you should do is to spawn a new background thread with a blocking listener (non asynchronous) and then use a new thread to read the data while the listener continues to listen.
I have an example here.
private static Socket s_chatListener;
public static void Listen(IPAddress LocalIPAddress, int Port)
{
IPEndPoint ipend = new IPEndPoint(LocalIPAddress, Port);
s_chatListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s_chatListener.Bind(ipend);
s_chatListener.Listen(10);
while (true)
{
Socket handler = s_chatListener.Accept();
ParameterizedThreadStart pst = new ParameterizedThreadStart(loadMessageFromSocket);
Thread t = new Thread(pst);
t.Start(handler);
}
}
private static void loadMessageFromSocket(object socket)
{
Socket handler = (Socket)socket;
string data = "";
while (true)
{
byte[] butes = new byte[1024];
int rec = handler.Receive(butes);
data += ASCIIEncoding.ASCII.GetString(butes);
if (data.IndexOf("\0") > -1)
break;
}
handler.Shutdown(SocketShutdown.Both);
handler.Close();
Console.Write(data);
}
Now just call the Listen Method from a new Thread in your main form or caller class.
Hope this helps.