Receiving and sending data in C# - c#

I'm still trying to improve a little bit what I wrote before.
Now I faced a problem with receiving data. I have a program which I use to send string using tcpClient to a program in which Im listening on a specified port. It works fine so I decided to send data forward one more time
public static void receiveThread()
{
while (true)
{
TcpListener tcpListener = new TcpListener(IPAddress.Any, port);
tcpListener.Start();
Console.WriteLine("Waiting for connection...");
TcpClient tcpClient = tcpListener.AcceptTcpClient();
Console.WriteLine("Connected with {0}", tcpClient.Client.RemoteEndPoint);
while (!(tcpClient.Client.Poll(20, SelectMode.SelectRead)))
{
NetworkStream networkStream = tcpClient.GetStream();
StreamReader streamReader = new StreamReader(networkStream);
data = streamReader.ReadLine();
if (data != null)
{
Console.WriteLine("Received data: {0}", data);
send(data); // Here Im using send Method
}
}
Console.WriteLine("Dissconnected...\n");
tcpListener.Stop();
}
}
/// <summary>
/// Sending data
/// </summary>
/// <param name="data">Data to send</param>
public static void send(string data)
{
TcpClient tcpClient = new TcpClient();
try
{
tcpClient.Connect(ipAddress, sendPort);
Console.WriteLine("Connected with {0}", tcpClient.Client.RemoteEndPoint);
}
catch (Exception e)
{
Console.WriteLine(e);
}
if (tcpClient.Connected)
{
NetworkStream networkStream = tcpClient.GetStream();
StreamWriter streamWriter = new StreamWriter(networkStream);
Console.WriteLine("Messege {0} to {1}", data, tcpClient.Client.RemoteEndPoint);
streamWriter.WriteLine(data);
streamWriter.Flush();
tcpClient.Close();
}
}
Sometimes it works fine, but more often, lets call it a receiver, can't get what Im trying to send. And I really do not konw what is wrong with it. Looks like there can be a problem with send method. Here is an example of receivers output
Waiting for connection...
Connected with 127.0.0.1:52449
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52450
Received data: qweqwe
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52451
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52452
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52453
Received data: zxczx
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52454
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52455
Received data: aasd
Dissconnected...
Waiting for connection...
Connected with 127.0.0.1:52457
Received data: www
Dissconnected...

Several problems here:
StreamReader has a 4kB buffer and will try to read as much as possible in the first call to ReadLine(). The result is that you might have data in the StreamReader and go into Poll() when there's no more data available because it's already been read.
Poll() takes microseconds. Waiting 0.02ms for incoming data is likely to return false unless the data is there before you call Poll().
You create a new StreamReader on every iteration, which might discard data already read in the previous one.
If you're just going to read lines and want a timeout and a StreamReader, I would do something like:
delegate string ReadLineDelegate ();
...
using (NetworkStream networkStream = tcpClient.GetStream()) {
StreamReader reader = new StreamReader(networkStream);
ReadLineDelegate rl = new ReadLineDelegate (reader.ReadLine);
while (true) {
IAsyncResult ares = rl.BeginInvoke (null, null);
if (ares.AsyncWaitHandle.WaitOne (100) == false)
break; // stop after waiting 100ms
string str = rl.EndInvoke (ares);
if (str != null) {
Console.WriteLine ("Received: {0}", str);
send (str);
}
}
}

Ensure that the data actually exists on the stream before chasing ghosts. If there is ALWAYS data we can approach the problem, however looking at it logically it appears as though the stream is either being nulled out or there is just no data on it.

Related

Receiving messages and sending messages over NetworkStream to a Client

I have a question about sending and receiving messages from a TCPListener server to a client over a Network Stream in C#. Right now, my TCPListener instance can receive one message from a client and write it to the server console, and it can accept one input string and send it back to the client. But I wish to improve the function to accept multiple consecutive messages from a client and send multiple consecutive responses back to the client. Does anyone happen to have any pointers if the ReadAsync and WriteAsync functions of a NetworkStream can handle receiving multiple consecutive messages or sending multiple consecutive messages and if there is a better method to achieve this? Also, since the Console.ReadLine function will block in the case the server never receives any user input from ReadLine (and no Enter key is pushed), is there a way to test if there's optional user input from the keyboard? That way I could try to execute the send message commands only if the server received some kind of console input from the user, and could continue receiving client messages otherwise.
public static async Task getMessage(TcpListener server)
{
byte[] bytes = new byte[256];
using (var theStream = await server.AcceptTcpClientAsync())
{
using (var tcpStream = theStream.GetStream())
{
await tcpStream.ReadAsync(bytes, 0, bytes.Length);
var msg = Encoding.UTF8.GetString(bytes);
Console.WriteLine(msg);
var payload = Console.ReadLine();
var bytes2 = Encoding.UTF8.GetBytes(payload);
await tcpStream.WriteAsync(bytes2, 0, bytes2.Length);
}
}
}
It is interesting to see a server implementation dedicated to only one client!
TCP is a two-way communication protocol so yes, you can, of course, send what you want and when you want and receive anything at the same time.
I tried to put comments in the source to let it explain itself.
But the critical point is declaring the TcpClient and NetworkStream instances as static variables so that the main thread (the thread which reads from the console and sends the payload to the client) can access them
Hope this helps.
public static async Task getMessage(TcpListener server)
{
byte[] bytes = new byte[256];
using (theStream = await server.AcceptTcpClientAsync())
{
using (tcpStream = theStream.GetStream())
{
// We are using an infinite loop which ends when zero bytes have been received.
// Receiving zero bytes means the transmission is over (client disconnected)
while (await tcpStream.ReadAsync(bytes, 0, bytes.Length) > 0)
{
var msg = Encoding.UTF8.GetString(bytes);
Console.WriteLine(msg);
}
Console.WriteLine("Client has disconnected");
}
}
}
/// <summary>
/// Transmists the payload to the client
/// </summary>
/// <param name="payload">The payload to transmit to the client</param>
/// <returns></returns>
static async Task Transmit(string payload)
{
var bytes2 = Encoding.UTF8.GetBytes(payload);
await tcpStream.WriteAsync(bytes2, 0, bytes2.Length);
}
// We are declaring the TcpClient and NetworkStream as static variables
// to be able to access them from all the threads.
private static TcpClient theStream;
public static NetworkStream tcpStream;
static void Main(string[] args)
{
TcpListener server = new TcpListener(IPAddress.Loopback, 9876);
server.Start();
// Start the task getMessage() to accept a client and receive
Task.Run(() => getMessage(server));
string payload;
while ((payload = Console.ReadLine()) != "exit")
{
// Check if the client has connected.
if (tcpStream != null)
{
// Check if they are still connected
if (theStream.Client.Connected)
{
Task.Run(() => Transmit(payload));
}
else
{
Console.WriteLine("the client connection is lost");
break;
}
}
else
{
Console.WriteLine("The client has not connected yet.");
}
}
Console.WriteLine("Stopping the server");
server.Stop();
}

How can we send the data using TcpListener in c#?

As per MSDN:
The TcpListener class provides simple methods that listen for and accept incoming connection requests in blocking synchronous mode.
My team lead is asking to send the data using TcpListener. Is there any way or feasible to receive as well as send the data using TCPListerner ?
I already know how to receive the data using TCPListener, don't have any idea about sending the data with the same. I know TCPClient can be used to send the data but our team lead wants to do it using TCPListerner.
Please let me know your comments and let me know if it is feasible with some sample code.
Not really. The purpose of TcpListener is to accept a new connection.
However, the stream object you get from your TcpListener (once the connection is established) can be used for reading and writing.
Look here for more details:
https://msdn.microsoft.com/en-us/library/system.net.sockets.tcplistener%28v=vs.110%29.aspx
using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Text;
class MyTcpListener
{
public static void Main()
{
TcpListener server=null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
// Enter the listening loop.
while(true)
{
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
data = null;
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(bytes, 0, bytes.Length))!=0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);
Console.WriteLine("Received: {0}", data);
// Process the data sent by the client.
data = data.ToUpper();
byte[] msg = System.Text.Encoding.ASCII.GetBytes(data);
// Send back a response.
stream.Write(msg, 0, msg.Length);
Console.WriteLine("Sent: {0}", data);
}
// Shutdown and end connection
client.Close();
}
}
catch(SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
}

Socket read freezes

I'm working on small program for learning purpose.
My program is simple Telnet console.
Using visual studio 2010 Express I created pretty cool UI now I'm trying to establish communication with remote server(Creston control processor). I copied and pasted class from this Microsoft article and when I execute the class the program freezes. I'm not sure how to properly describe what happens but in basic word all controls(including close button) stop working.
Here code for my class:(I added few debug lines);
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 256;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
public string TempString = string.Empty;
public int TotalBytesRead = 0;
public char[] charBuffer = new char[1000];
}
public class AsynchronousClient
{
// The port number for the remote device.
private const int port = 23;
// ManualResetEvent instances signal completion.
private static ManualResetEvent connectDone =
new ManualResetEvent(false);
private static ManualResetEvent sendDone =
new ManualResetEvent(false);
private static ManualResetEvent receiveDone =
new ManualResetEvent(false);
// The response from the remote device.
private static String response = String.Empty;
public AsynchronousClient()
{
}
public void New()
{
StartClient();
}
private static void StartClient()
{
// Connect to a remote device.
try
{
// Establish the remote endpoint for the socket.
// The name of the
// remote device is "host.contoso.com".
IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("10.106.6.60"), port);
// Create a TCP/IP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Connect to the remote endpoint.
client.BeginConnect(remoteEP,
new AsyncCallback(ConnectCallback), client);
connectDone.WaitOne();
Console.WriteLine("StartSend");
// Send test data to the remote device.
//Send(client, "hostname\n");
//sendDone.WaitOne();
Console.WriteLine("WaitForResponse");
// Receive the response from the remote device.
Receive(client);
receiveDone.WaitOne();
// Write the response to the console.
Console.WriteLine("Read From Socket : {0}", response);
Console.WriteLine("ReleaseSocket");
// Release the socket.
client.Shutdown(SocketShutdown.Both);
client.Disconnect(true);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ConnectCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete the connection.
client.EndConnect(ar);
Console.WriteLine("Socket connected to {0}",
client.RemoteEndPoint.ToString());
// Signal that the connection has been made.
connectDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Receive(Socket client)
{
try
{
// Create the state object.
Console.WriteLine("Receive");
StateObject state = new StateObject();
state.workSocket = client;
// Begin receiving the data from the remote device.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void ReceiveCallback(IAsyncResult ar)
{
try
{
// Retrieve the state object and the client socket
// from the asynchronous state object.
Console.WriteLine("Start Read");
StateObject state = (StateObject)ar.AsyncState;
Socket client = state.workSocket;
// Read data from the remote device.
int bytesRead = client.EndReceive(ar);
Console.WriteLine("Bytes read: {0}", bytesRead);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
string tsTempString = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
state.TempString += tsTempString;
Console.WriteLine("String {0}", tsTempString);
state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));
// Get the rest of the data.
client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
}
else
{
// All the data has arrived; put it in response.
if (state.sb.Length > 1)
{
response = state.sb.ToString();
}
// Signal that all bytes have been received.
receiveDone.Set();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
private static void Send(Socket client, String data)
{
Console.WriteLine("Send");
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
client.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), client);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
Console.WriteLine("SendCallBack");
// Retrieve the socket from the state object.
Socket client = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = client.EndSend(ar);
Console.WriteLine("Sent {0} bytes to server.", bytesSent);
// Signal that all bytes have been sent.
sendDone.Set();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
When connecting to the server it responds with following lines:
CP3 Console
Warning: Another console session is open
CP3>
When I run the program i get following output:
Socket connected to 10.106.6.60:23
StartSend
WaitForResponse
Receive
Start Read
Bytes read: 13
String CP3 Console
Start Read
Bytes read: 43
String Warning: Another console session is open
Start Read
Bytes read: 6
String
CP3>
The thread '<No Name>' (0x1d80) has exited with code 0 (0x0).
The thread '<No Name>' (0x24bc) has exited with code 0 (0x0).
I tried different methods of reading stream but no successes. The program still hangs up at the same spot.
It seems as after reading last byte ">" the program does not re-executes method "ReceiveCallback" to exit out of the loop.
I get feeling it has something with the way "ReceiveCallback" is being called but I could not figure out what client.beginReceive() parameters actually do.
To expand on Roemer's answer: EndReceive will return 0 only if the conversation has terminated. That usually means a TCP packet with the FIN or RST flag has been received, most often because the peer - in your case, the server - closed its endpoint or exited. (There are various other cases; for example, a firewall or intermediate node could generate an RST.)
(Roemer wrote "BeginReceive never returns zero...", but clearly meant EndReceive, since BeginReceive returns the IAsyncResult object.)
If the peer doesn't close its end of the conversation, EndReceive won't return 0, and you'll never enter the else branch of your callback that invokes receiveDone.Set().
It's not entirely clear from your description exactly how the server behaves, but its last send of 6 bytes was clearly a newline followed by the "CP3>" prompt. At that point it's waiting for your client to send something. It's not going to close the connection.
TCP is a bytestream service - it doesn't provide record boundaries. So there's no way for the socket layer to know when the server is "done sending", except when the server closes the connection. You have three choices for your client:
Parse the server's output as you receive it and recognize when it's waiting for input (in this case, that means recognizing the "CP3>" prompt)
Decide the server's done after some arbitrary time has passed with no further data from the server
Don't worry about it, and simply output data from the server as you receive it
That third option is the simplest one. Do your first BeginReceive after making the connection. Then, in your callback method, if the conversation is still open and no errors have occurred, process the data you've received and invoke BeginReceive again.
To be honest, this example from microsoft is really bad.
In general, client.EndReceive never returns 0 except when the connection is closed. So receiveDone.Set will never be called in your example. In a more real-live example, you should check the received data in ReceiveCallback and when a keyword (like "Login: ") occurs, set the receiveDone and start sending (the login data for example) and the start receiving again and so on. You might also want to look at the async/await keyword (.net 4.5) and maybe upgrade to Visual Studio community edition :)
There are tons of examples on codeproject or found via google (like http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx).

TCPClient not receiving data

I want to use StreamReader and StreamWriter to receive and send data over TCPClient.NetworkStream. The code is depicted below:
Client code:
using (TcpClient client = new TcpClient())
{
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 9001);
client.Connect(localEndPoint);
client.NoDelay = true;
using(NetworkStream stream = client.GetStream())
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
using (StreamReader reader = new StreamReader(stream))
{
string message = "Client says: Hello";
writer.WriteLine(message);
// If I comment the line below, the server receives the first message
// otherwise it keeps waiting for data
string response = reader.ReadToEnd();
Console.WriteLine(response);
}
;
}
}
}
Note: If I comment the reader.ReadToEnd(); then the server receives the message, otherwise the server keeps waiting for data from the client. Is ReadToEnd the problem?
Server code accepts a connection asynchronously, but handles the data in a synchronous manner:
class Program
{
private static AsyncCallback tcpClientCallback;
static void Main(string[] args){
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"),9001);
TcpListener listener = new TcpListener(localEndPoint);
listener.Start();
tcpClientCallback = new AsyncCallback(ConnectCallback);
AcceptConnectionsAysnc(listener);
Console.WriteLine("Started Aysnc TCP listener, press any key to exit (server is free to do other tasks)");
Console.ReadLine();
}
private static void AcceptConnectionsAysnc(TcpListener listener)
{
listener.BeginAcceptTcpClient(tcpClientCallback, listener);
}
static void ConnectCallback(IAsyncResult result)
{
Console.WriteLine("Received a conenct request");
TcpListener listener = (TcpListener)result.AsyncState;
// We are starting a thread which waits to receive the data
// This is not exactly scalable
Task recieveTask = new Task(() => { HandleRecieve(result, listener); });
recieveTask.Start();
AcceptConnectionsAysnc(listener);
}
// This makes a blocking call - that means until the client is ready to
// send some data the server waits
private static void HandleRecieve(IAsyncResult result, TcpListener listener)
{
Console.WriteLine("Waiting for data");
using (TcpClient client = listener.EndAcceptTcpClient(result))
{
client.NoDelay = true;
using (NetworkStream stream = client.GetStream())
{
using (StreamReader reader = new StreamReader(stream))
{
using (StreamWriter writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
Stopwatch watch = new Stopwatch();
watch.Start();
string data = reader.ReadToEnd();
watch.Stop();
Console.WriteLine("Time: " + watch.Elapsed.TotalSeconds);
Console.WriteLine(data);
// Send a response to client
writer.WriteLine("Response: " + data);
}
}
}
}
}
}
A stream doesn't end until it is closed. Currently, both client and server are holding their connections open, and both is trying to read to the end from the other - and when they do, will close themselves. This is a deadlock: neither will ever get to the end, so neither will ever close (which would allow the other to get to the end).
Options:
use raw sockets, and have the client close the outbound stream after sending:
socket.Shutdown(SocketShutdown.Send);
this lets the server read to completion, which lets the server close, which lets the client read to completion; the client can still read from the inbound stream after closing the outbound socket.
use a different termination metaphor than ReadToEnd; for text-based protocols, end-of-line is the most common (so: ReadLine); for binary protocols, a length-prefix of the message is the most common. This allows each end to read the next message, without ever having to read to the end of the stream. In this scenario it would only be a single message, but the strategy still works.
use a different protocol if you find the above tricky; http is good for single request/response operations, and can be handled at the server via HttpListener.
Additionally, I'd be very careful about using ReadToEnd on a server (or even ReadLine) - that could be a good way of locking up threads on the server. If the server needs to cope with high throughput and lots of connections, async-IO based on raw sockets would be preferred.

Unable to Read byte Stream in C#

I am building a client server application where a client has to send some byte stream and the server responds to it based on the bytes received from the Client. I am using the NetworkStream.Write and NetworkStream.Read methods to send and receive data. The client is able to create a TCP connection to the server. After accepting the connection, the server does NetworkStream.Read and waits for some input from the client. The Client sends the data using the NetworkStream.Write and also does NetworkStream.Flush. But the Server never wakes up from the Read.
Can you guys suggest me what could be the problem here or if you know any other methods to send Byte Stream over a TCP Connection in C# please let me know.
Thanks!
Smart-ass comments aside: even though you are only interested in 2 lines of code, I'm willing to bet your problem is someplace else in your code.
Using a modified version of the code found here, I constructed a simple example that works in my testing.
public static void Main()
{
TcpListener server = null;
try
{
// Set the TcpListener on port 13000.
Int32 port = 13000;
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
// TcpListener server = new TcpListener(port);
server = new TcpListener(localAddr, port);
// Start listening for client requests.
server.Start();
// Buffer for reading data
Byte[] bytes = new Byte[256];
Console.Write("Waiting for a connection... ");
// Perform a blocking call to accept requests.
// You could also user server.AcceptSocket() here.
TcpClient client = server.AcceptTcpClient();
Console.WriteLine("Connected!");
// Get a stream object for reading and writing
NetworkStream stream = client.GetStream();
stream.Read(bytes, 0, bytes.Length);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(bytes));
// Shutdown and end connection
client.Close();
}
catch (SocketException e)
{
Console.WriteLine("SocketException: {0}", e);
}
finally
{
// Stop listening for new clients.
server.Stop();
}
Console.WriteLine("\nHit enter to continue...");
Console.Read();
}
The read call will wait and return when I send it 1 byte with another program. We would need to see some code to figure out why this works and yours does not.

Categories

Resources