I am having a problem sending information down a socket and receiving a response. I have a demo program which is performing correctly so I know it is not an issue with the client on the other end.
The requestData is sent and the client acts correctly and responds, but my code never exits the loop in read response.
Could the client be responding before I am listening? How can I make sure I never miss an incoming message?
networkStream = tcpClient.GetStream();
StreamWriter clientStreamWriter = new StreamWriter();
clientStreamWriter.WriteLine(requestData);
clientStreamWriter.Flush();
// Continuously read data on the socket and if it is more than just a ping, read the response.
StringBuilder sbReadBuffer = new StringBuilder();
while (true)
{
String response = readresponse(timeoutOn30Seconds);
if (response.Length > 1 && (!response.Contains("\r\n") || response.Contains(",")))
{
break;
}
}
sbReadBuffer.Append(received);
return sbReadBuffer.ToString();
readResponse:
private string readresponse(Boolean timeoutOn30Seconds)
{
// Get network stream.
DateTime lastConTime = DateTime.Now;
Int32 i = 0;
// Start listening to stream.
while (!networkStream.DataAvailable)
{
Log.W(".");
// Only check every 10ms.
Thread.Sleep(10);
// If no response in 30mins stop listening and give an offline warning.
if ((DateTime.Now - lastConTime).TotalSeconds > tcpClient.ReceiveTimeout)
{
received = "CLIENT NOT FOUND";
return received;
}
// Only check if application online every 1s.
if (i > 100)
{
if (Process.GetProcessesByName(ConfigurationManager.AppSettings["ClientName"]).FirstOrDefault() == null && Convert.ToInt32(ConfigurationManager.AppSettings["Device"]) != 680)
{
received = "CLIENT NOT FOUND";
return received;
}
i = 0;
}
i++;
}
// If data has been writted to the buffer, read it out and assign output variable and return that string for length comparison.
byte[] receiveBuffer = new byte[tcpClient.ReceiveBufferSize];
Int32 receiveCount = networkStream.Read(receiveBuffer, 0, receiveBuffer.Length);
received = new ASCIIEncoding().GetString(receiveBuffer, 0, receiveCount);
return received;
}
DataAvailable isn't a good method to know if data are coming, especially in a while loop that is surely faster than network communications.
A better way could be to use the Read method (bytes read) to know where data are available, into a timed loop; so change your while condition in this manner (and then adjust the other parts)
while (networkStream.Read(receiveBuffer, 0, receiveBuffer.Length) > 0)
{
Log.W(".");
// Only check every 10ms.
Thread.Sleep(10);
but I prefer, if possible, an async approach, so your client will be notified when data are incoming.
See this answer that use this kind of approach.
Basically set an async callback that will be fired when data are coming
public void StartListening() {
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPEndPoint localEP = new IPEndPoint(ipHostInfo.AddressList[0],11000);
Console.WriteLine("Local address and port : {0}",localEP.ToString());
Socket listener = new Socket( localEP.Address.AddressFamily,
SocketType.Stream, ProtocolType.Tcp );
try {
listener.Bind(localEP);
listener.Listen(10);
while (true) {
allDone.Reset();
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(SocketListener.acceptCallback),
listener );
allDone.WaitOne();
}
} catch (Exception e) {
Console.WriteLine(e.ToString());
}
Console.WriteLine( "Closing the listener...");
}
and there you can read your data
public static void acceptCallback(IAsyncResult ar) {
// Get the socket that handles the client request.
Socket listener = (Socket) ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Signal the main thread to continue.
allDone.Set();
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(AsynchronousSocketListener.readCallback), state);
}
Here full MSDN documentation
You dont read in while loop. To clear DataAvailable flag, you have to read from networkStream.
Sample usage :
http://msdn.microsoft.com/en-us/library/system.net.sockets.networkstream.dataavailable%28v=vs.100%29.aspx
Related
I have a simple asynchronous socket server written in C# (pretty much Microsoft's example), however the issue with this example is that it accepts only one message from a client and then shuts down. I want this server to stay alive after receiving any message.
This question has been asked before here, and the answer & comments explain that the resolution to this is simply to call handler.beginReceive within the SendCallback function, however to do this requires passing in a state variable. This is something I am unsure of doing with Async programming as I'm pretty new to it.
With the example below, how can I carry my state object from the Send function to the SendCallback function?
Server code:
// Asynchronous Server Socket Example
// http://msdn.microsoft.com/en-us/library/fx6588te.aspx
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class GetState
{
}
public class AsynchronousSocketListener
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 11000);
// Create a TCP/IP socket.
Socket listener = new Socket(ipAddress.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback), listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content != null)
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content);
// Echo the data back to the client.
Send(handler, content, state);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
}
}
private static void Send(Socket handler, String data, StateObject state)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
/// ******* WIP ******** //
//handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
//handler.Shutdown(SocketShutdown.Both);
//handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
This is how I would do it:
public class AsynchronousSocketServer
{
private Socket listener;
private byte[] buffer = new byte[8192]; // Buffer to store data from clients.
public void StartListening()
{
listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listener.Bind(new IPEndPoint(localIPAddress, listeningPort));
listener.Listen(20);
listener.BeginAccept(OnSocketAccepted, null);
}
private void OnSocketAccepted(IAsyncResult result)
{
// This is the client socket, where you send/receive data from after accepting. Keep it in a List<Socket> collection if you need to.
Socket client = listener.EndAccept(result);
// Pass in the client socket as the state object, so you can access it in the callback.
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnDataReceived, client); // Start receiving data from this client.
listener.BeginAccept(OnSocketAccepted, null); // Start a new async accept operation to accept incoming connections from other clients.
}
private void OnDataReceived(IAsyncResult result)
{
// This is the client that sent you data. AsyncState is exactly what you passed into the state parameter in BeginReceive
Socket client = result.AsyncState as Socket;
int received = client.EndReceive(result);
// Handle received data in buffer, send reply to client etc...
// Start a new async receive on the client to receive more data.
client.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, OnDataReceived, client);
}
}
As you can see it's pretty much a lot of recursive callbacks. The basic idea is that you call BeginAccept to start accepting the first connection, then once your callback fires you accept the connection with EndAccept and start a new BeginAccept to start accepting more connections. This same logic applies to BeginReceive and EndReceive when you start communicating with the clients. With this logic the server will continuously accept incoming connections and clients will also be able to continously send data to server.
In your example you get your listener from the AsyncState but you didn't call BeginAccept again to accept more incoming connections, which probably explains why your server only accepts 1 connection and shuts down.
For the state parameter in BeginSend, you can actually just put your BeginReceive right after your Send() method to save yourself the hassle:
Send(handler, content, state);
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
It's much better to just fire up a background thread and use blocking calls.
Here's a TcpServer using the TcpListener and NetworkStream
public class TcpServer
{
public void Run(string address, int port)
{
var listener = new TcpListener(IPAddress.Parse(address), port);
listener.Start();
while (true)
{
TcpClient tcpclient = null;
NetworkStream netstream = null;
try
{
tcpclient = listener.AcceptTcpClient();
Console.WriteLine("Client connected from " + tcpclient.Client.LocalEndPoint.ToString());
netstream = tcpclient.GetStream();
var responsewriter = new StreamWriter(netstream) { AutoFlush = true };
while (true)
{
if (IsDisconnected(tcpclient))
throw new Exception("Client disconnected gracefully");
if (netstream.DataAvailable) // handle scenario where client is not done yet, and DataAvailable is false. This is not part of the tcp protocol.
{
string request = Read(netstream);
Console.WriteLine("Client sent: " + request);
responsewriter.Write("You sent: " + request);
}
}
}
catch (Exception ex)
{
netstream.Close();
tcpclient.Close();
Console.WriteLine(ex.Message);
}
}
}
private bool IsDisconnected(TcpClient tcp)
{
if (tcp.Client.Poll(0, SelectMode.SelectRead))
{
byte[] buff = new byte[1];
if (tcp.Client.Receive(buff, SocketFlags.Peek) == 0)
return true;
}
return false;
}
private string Read(NetworkStream netstream)
{
byte[] buffer = new byte[1024];
int dataread = netstream.Read(buffer, 0, buffer.Length);
string stringread = Encoding.UTF8.GetString(buffer, 0, dataread);
return stringread;
}
}
To run it
static void Main()
{
ThreadPool.QueueUserWorkItem(w => {
var asyncserver = new TcpServer();
asyncserver.Run("192.168.0.7", 5055); // or whatever your local IP Address is
});
Console.WriteLine("Press [Enter] to quit");
Console.ReadLine();
}
I am using sockets for TCP-IP connection and I would like to establish simple system send-receive from the client side.
Socket sck;
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint localEndpt = new IPEndPoint(IPAddress.Parse("123.123.123.1"), 12345);
try
{
sck.Connect(localEndpt);
}
catch
{
Console.Write("Unable to Connect");
}
while (true)
{
Console.WriteLine("Enter Text");
string sendtext = Console.ReadLine();
byte[] Data = Encoding.ASCII.GetBytes(sendtext);
sck.Send(Data);
Console.WriteLine("Data Sent!");
byte[] bytesReceived = new byte[sck.ReceiveBufferSize];
int bytes = 0;
String strReceived = "";
int dataAvailable = 0;
while (dataAvailable == 0 || dataAvailable != sck.Available)
{
dataAvailable = sck.Available;
Thread.Sleep(100); // if no new data after 100ms assume transmission finished
}
if (sck.Available > 0)
{
bytes = sck.Receive(bytesReceived, bytesReceived.Length, 0);
strReceived+=Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
Console.WriteLine("Received from server: " + strReceived);
}
Console.Read();
The problem is that first requests goes throught but the second does not, because socket is not available anymore (socket "Availabe" attribute value is 0). What am I doing wrong? What would be the easiest way to establish multiple send-recieve requests (in order)?
This code works fine for me
private List<Socket> _clients = new List<Socket>();
private Thread _dataReceiveThread;
private bool _isConnected;
private void DataReceive()
{
while (_isConnected)
{
List<Socket> clients = new List<Socket>(_clients);
foreach (Socket client in clients)
{
try
{
if (!client.Connected) continue;
string txt = "";
while (client.Available > 0)
{
byte[] bytes = new byte[client.ReceiveBufferSize];
int byteRec = client.Receive(bytes);
if (byteRec > 0)
txt += Encoding.UTF8.GetString(bytes, 0, byteRec);
}
if (!string.IsNullOrEmpty(txt))
/* TODO: access the text received with "txt" */
}
catch (Exception e)
{
Exception_Handler(e);
}
}
}
}
Just run this code to get started
_isConnected = true;
_dataReceiveThread = new Thread(DataReceive);
_dataReceiveThread.Start();
Update list box in Cross thread:
This code can be placed in the comment section.
myListBox1.Invoke((Action)(() => { myListBox1.Items.Add(txt) }));
Socket. Available does NOT indicate whether the socket is available, but incoming data is available for reading:
https://msdn.microsoft.com/en-us/library/ee425135.aspx
Your program quits because it checks for a reply (incoming data) immediately after sending a message out. Use a Thread.Sleep before checking for data.
Maybe the message has not even been sent, because Socket.Send just places it in the network interface card's output buffer. When the socket finally sends the message, it will upare the connection state. If it got no reply (on a TCP connection), it will tell you that it is disconnected when you query the state. On UDP it will tell you nothing, because UDP is connectionless.
I am writing some socket server, client application and I have a major problem. My goal is to create an async Server App in C# and a basic client APP in python. When I do follow simple examples both program work. But when I write an async Server with read and write handler messages being send from the client APP, it does not work.
Here is the example Server code that I am using.
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 3333);
IPEndPoint ipLocal = new IPEndPoint(IPAddress.Any, 3333);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(ipLocal);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
Console.WriteLine("\n Enters(0)");
if (bytesRead > 0)
{
Console.WriteLine("\n Enters(1)");
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
if (content.IndexOf("<EOF>") > -1)
{
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content);
// Echo the data back to the client.
Send(handler, content);
}
else
{
Console.WriteLine("\n Detect");
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
Console.WriteLine("\n Enters(1)");
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(String[] args)
{
StartListening();
return 0;
}
}
and here is the python code for a simple test client
import socket
HOST, PORT = "127.0.0.1", 3333
data = "data"
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((HOST, PORT))
sock.sendall(data)
print data
finally:
sock.close()
As I have inserted some debug code on Server's ReadCallback, I see that the routine is called, but it doesn't process the received data as a message. It doesn't seem to have an endpoint.
Any ideas or solutions will be appreciated.
Your ReadCallback ignores the case when bytesRead == 0, which means the client stopped sending data. If your Python code is actually sending "data" without "<EOF>", then your connection is simply forgotten by the C# server.
Regarding your C# code, there are a few things you could improve:
Use ManualResetEventSlim, it's faster, it doesn't use an operating system handle (unless you actually use the WaitHandle property)
You should handle exceptions from EndAccept in AcceptCallback and EndReceive in ReadCallback, and probably improve exception handling in SendCallback
You're creating a string from your StringBuilder in ReadCallback every time, which goes totally against the purpose of using a StringBuilder; you should parse each string you get from Encoding.ASCII.GetString to search for each character, <, E, O, F and > in succession
// Add to StateObject
public const string EOF = "<EOF>";
public int eofOffset = -1;
public int searchOffset = 0;
// In ReadCallback
string data = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
state.sb.Append(data);
int o = state.searchOffset + state.eofOffset + 1;
while (o < state.sb.Length)
{
if (state.sb[o] != StateObject.EOF[state.eofOffset + 1])
{
state.eofOffset = -1;
state.searchOffset++;
o = state.searchOffset;
}
else
{
state.eofOffset++;
if (state.eofOffset == StateObject.EOF.Length)
{
break;
}
o++;
}
}
// Replace this:
//content = state.sb.ToString();
//if (content.IndexOf("<EOF>") > -1)
// with this:
if (state.eofOffset == StateObject.EOF.Length)
{
// Here is a good place to turn the StringBuilder into a string
// Perhaps truncate data to send back up to state.searchOffset
// ...
}
Not an expert for C#, but I think You have problem with Python program.
try:
sock.connect((HOST, PORT))
sock.sendall("data")
print data
finally:
sock.close()
You're trying to print data, which is not defined. Therefore, except part would be executed (if it existed). Then, program is finished with socket being closed.
i have written(Copied) code for a tcpip server.
We have software that sends a message via TCPIP and expects a return message back to say Receive is Acknowledged. This works fine. But after sending the acknowledgment the connection drops out. I am not sure where in the code this dropout is occurring. So when the next message is sent, there is no connection so it does a rollback and reconnects again and then send the message. So every time i send multiple messages i will keep getting rollback alerts. We will be constantly sending messages all day long. Below is the code :
class Program
{
// State object for reading client data asynchronously
public class StateObject
{
// Client socket.
public Socket workSocket = null;
// Size of receive buffer.
public const int BufferSize = 1024;
// Receive buffer.
public byte[] buffer = new byte[BufferSize];
// Received data string.
public StringBuilder sb = new StringBuilder();
}
public class AsynchronousSocketListener
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
public AsynchronousSocketListener()
{
}
public static void StartListening()
{
// Data buffer for incoming data.
byte[] bytes = new Byte[1024];
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
ipAddress = IPAddress.Parse("127.0.0.1");
IPEndPoint localEndPoint = new IPEndPoint(ipAddress, 8080);
// Create a TCP/IP socket.
Socket listener = new Socket(AddressFamily.InterNetwork,
SocketType.Stream, ProtocolType.Tcp);
// Bind the socket to the local endpoint and listen for incoming connections.
try
{
listener.Bind(localEndPoint);
listener.Listen(100);
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(
new AsyncCallback(AcceptCallback),
listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
Console.WriteLine("\nPress ENTER to continue...");
Console.Read();
}
public static void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
ar.AsyncWaitHandle.WaitOne(100);
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
StateObject state = new StateObject();
state.workSocket = handler;
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
public static void ReadCallback(IAsyncResult ar)
{
String content = String.Empty;
String s1 = "MSH|^~\\&|BB|NSCCH|MILLENNIUM|BB|20150522080258137||ACK";
String s2 = "|20150522080258137883|P|2.4";//\r\nMSA|AA|Q245548634T287475114";
//String s3 = String.Empty;
String s4 = "MSA|AA|Q245548634T287475114";
//string s5 = "0x02";
int value = Convert.ToInt32("0x1C", 16);
char cc = (char)value;
int value_eob = Convert.ToInt32("0x0b", 16);
char eob = (char)value_eob;
int value_eod = Convert.ToInt32("0x0D", 16);
char eod = (char)value_eod;
int value_eoa = Convert.ToInt32("0x0A", 16);
char eoa = (char)value_eoa;
/*StringBuilder sb1 = new StringBuilder(s5);
sb1.Append(s1);
sb1.Append(s2);
s3 = sb1.ToString();*/
//byte[] s4 = Encoding.ASCII.GetBytes(s3);
// Retrieve the state object and the handler socket
// from the asynchronous state object.
StateObject state = (StateObject)ar.AsyncState;
Socket handler = state.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
state.sb.Append(Encoding.ASCII.GetString(
state.buffer, 0, bytesRead));
// Check for end-of-file tag. If it is not there, read
// more data.
content = state.sb.ToString();
//s3 = state.sb.ToString();
// s3 = s1.ToString() + s2.ToString();
if (bytesRead < 1024) //content.IndexOf("<EOF>") > -1)
{
string s6 = eob.ToString() + s1 + s2 + eod.ToString() + s4 + cc.ToString() + eod.ToString() + eoa.ToString();// "\r\n";// +cc.ToString() + "\r\n";
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content);
Console.WriteLine("Send {0} bytes from socket. \n Data : {1}",
s6.Length, s6);
// Echo the data back to the client.
Send(handler, s6);
}
else
{
// Not all data received. Get more.
handler.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
}
else
{
if (content.Length > 0)
{
string s6 = eob.ToString() + s1 + s2 + eod.ToString() + s4 + cc.ToString() + eod.ToString() + eoa.ToString();// "\r\n";// +cc.ToString() + "\r\n";
// All the data has been read from the
// client. Display it on the console.
Console.WriteLine("Read {0} bytes from socket. \n Data : {1}",
content.Length, content);
Console.WriteLine("Send {0} bytes from socket. \n Data : {1}",
s6.Length, s6);
// Echo the data back to the client.
Send(handler, s6);
}
}
// Added code
handler.BeginReceive(state.buffer,0, StateObject.BufferSize, 0,
new AsyncCallback(ReadCallback), state);
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0,
new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
try
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
Console.WriteLine("Sent {0} bytes to client.", bytesSent);
// handler.Shutdown(SocketShutdown.Both);
// handler.Close();
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
public static int Main(string[] args)
{
StartListening();
return 0;
}
}
}
You have at least two major bugs in your code:
You are assuming that a receive operation will always complete having filled the provided buffer, unless the client has stopped sending data (i.e. there's no more data to be received at the moment). This is often going to be true, but it is not guaranteed and your code will fail spuriously if it makes that assumption.
Once you believe that you have received all of the current transmission from the client, you do not call BeginReceive() again. This renders the connection completely useless from that point forward.
Another possible bug is:
Your code does not correctly partition transmitted data. There does not seem to be any code here that will reliably detect the boundary between two different logical messages in the stream of bytes received. Depending on how quickly data is sent by a client, it is possible that some or all data intended to be part of a later logical message is consumed as part of an earlier logical message.
Unfortunately, there is not enough precise detail provided in your question. The phrase "connection drops out" is non-specific and has no well-defined technical meaning. It could mean you get an error on the socket, or it could simply mean that you never receive any more data, or it could mean something else entirely.
That said, if you mean "never receive any more data", then I would say it is most likely that the #2 bug above is the basic cause of your problem. Of course, the #1 bug can in conjunction with the #2 bug also lead to "never receive any more data".
Without a good, minimal, complete code example that reliably reproduces the problem (please note that for network-related issues, a complete example includes both endpoints of the connection), it's impossible to know for sure all of the bugs in the code example, never mind what the actual problem is. However, I would recommend fixing the above bugs and see if that improves things.
As a general rule, your network code should run like this:
Receive data
Interpret the data, identifying logical message boundary (if any)
If a complete logical message has been received, process it. Be sure to retain any excess data that might have been received, for processing as part of the next logical message.
Continue the above, always initiating a new receive operation after handling the results of the current completed operation, until a receive operation completes with a byte count of zero.
When a zero-byte receive operation completes, complete processing of the data received so far (if there is any not yet processed) and acknowledge the graceful closure of the connection by sending any remaining data (if any) and calling Socket.Shutdown(SocketShutdown.Both), and only then calling Socket.Close() to actually close the socket.
I am using the MSDN server example found here
http://msdn.microsoft.com/en-us/library/fx6588te(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1
and my problem is that this code only continuously accepts new clients. I want it to continuously receive from all the clients that it accepts as well. This code accepts a client then receives one message from them and then sends one message and that's it. The only thing I can think to do is stick the async receive method in a while(true) loop, but that doesn't sound right.
I changed the example a little but it still has the same basic functionality.
public class AServer
{
// Thread signal.
public static ManualResetEvent allDone = new ManualResetEvent(false);
Socket listener;
ArrayList clients;
public AServer(int port)
{
// Establish the local endpoint for the socket.
// The DNS name of the computer
// running the listener is "host.contoso.com".
IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName());
IPAddress ipAddress = ipHostInfo.AddressList[0];
IPEndPoint localEndPoint = new IPEndPoint(IPAddress.IPv6Any, port);
clients = new ArrayList();
// Create a TCP/IP socket.
listener = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
listener.SetSocketOption(SocketOptionLevel.IPv6, (SocketOptionName)27, 0);
listener.Bind(localEndPoint);
listener.Listen(100);
}
public void ServerLoop(){
while (true)
{
// Set the event to nonsignaled state.
allDone.Reset();
// Start an asynchronous socket to listen for connections.
Console.WriteLine("Waiting for a connection...");
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
// Wait until a connection is made before continuing.
allDone.WaitOne();
}
}
public void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
ClientData state = new ClientData();
state.workSocket = handler;
clients.Add(state);
handler.BeginReceive(state.buffer, 0, ClientData.BufferSize, 0,new AsyncCallback(ReadCallback), state);
Console.WriteLine("we passed handler.BeginReceive");
}
public void ReadCallback(IAsyncResult ar)
{
// Retrieve the state object and the handler socket
// from the asynchronous state object.
ClientData data = (ClientData)ar.AsyncState;
String buff = String.Empty;
Socket handler = data.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
buff = Encoding.ASCII.GetString(data.buffer, 0, bytesRead);
ParseBuffer(buff);
Send(handler, "1");
}
if (bytesRead == 0) {
CloseConnection(handler);
}
}
private bool ParseBuffer(String buff) {
Console.WriteLine(buff);
switch (buff[0]) {
case '0':
break;
case '1':
break;
}
return true;
}
private static void Send(Socket handler, String data)
{
// Convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(data);
// Begin sending the data to the remote device.
handler.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), handler);
}
private static void SendCallback(IAsyncResult ar)
{
// Retrieve the socket from the state object.
Socket handler = (Socket)ar.AsyncState;
// Complete sending the data to the remote device.
int bytesSent = handler.EndSend(ar);
}
private static void CloseConnection(Socket handler)
{
handler.Shutdown(SocketShutdown.Both);
handler.Close();
}
}
Of course my main method simply calls the constructor then the loop sequentially. The arraylist is a remnant of some attempts of mine to figure this out.
edit
I was looking for the same sort of functionality that Select offers me in C, but apparently C# can do the same thing with events.
In your ReadCallback you need to post again an async Receive:
public void ReadCallback(IAsyncResult ar)
{
// Retrieve the state object and the handler socket
// from the asynchronous state object.
ClientData data = (ClientData)ar.AsyncState;
String buff = String.Empty;
Socket handler = data.workSocket;
// Read data from the client socket.
int bytesRead = handler.EndReceive(ar);
if (bytesRead > 0)
{
// There might be more data, so store the data received so far.
buff = Encoding.ASCII.GetString(data.buffer, 0, bytesRead);
ParseBuffer(buff);
Send(handler, "1");
// Here, you need to Receive again
handler.BeginReceive(state.buffer, 0, ClientData.BufferSize, 0,new AsyncCallback(ReadCallback), state);
}
if (bytesRead == 0) {
CloseConnection(handler);
}
}
This way you will receive, send, receive, send, receive, send etc on each socket. You need error handling and a proper server would need to handle incomplete messages, but that is the general idea.
BTW, similarly you must post another async Accept in your accept callback:
public void AcceptCallback(IAsyncResult ar)
{
// Signal the main thread to continue.
allDone.Set();
// Get the socket that handles the client request.
Socket listener = (Socket)ar.AsyncState;
Socket handler = listener.EndAccept(ar);
// Create the state object.
ClientData state = new ClientData();
state.workSocket = handler;
clients.Add(state);
handler.BeginReceive(state.buffer, 0, ClientData.BufferSize, 0,new AsyncCallback(ReadCallback), state);
Console.WriteLine("we passed handler.BeginReceive");
// Here, you must start a new accept:
listener.BeginAccept(new AsyncCallback(AcceptCallback),listener);
}