473,386 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Asynchronous Server Socket Problem

375 256MB
Hi,
We have an asynchronous server socket program, which works fine BUT, when due to some circumstances, I receive null data or blank data, the server goes to infinite loop
Here is the code

Expand|Select|Wrap|Line Numbers
  1. namespace SocketServer
  2. {
  3.  
  4.     public class StateObject  //class created to clear the duplicate records
  5.     {
  6.         // Client socket.
  7.         public Socket workSocket = null;
  8.         // Size of receive buffer.
  9.         public const int BufferSize = 5000;
  10.         // Receive buffer.
  11.         public byte[] buffer = new byte[BufferSize];
  12.         // Received data string.
  13.         public string sb;
  14.  
  15.     }
  16.  
  17.     class Program
  18.     {
  19.  
  20.  
  21.         public AsyncCallback pfnWorkerCallBack;
  22.         private Socket m_mainSocket;
  23.  
  24.         public int port = 7030;
  25.         public byte[] m_byBuff = new byte[5000];
  26.         public int flag2 = 0;
  27.  
  28.         public byte[] inValue = new byte[] { 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0 };
  29.         public byte[] outvalue = new byte[10];
  30.  
  31.         private string m_strConnection;
  32.         public Program()
  33.         {
  34.             this.m_strConnection = ConfigurationSettings.AppSettings["Connection"];
  35.             this.strDateFormat = null;
  36.             this.strLocation = null;
  37.             StartListen();
  38.  
  39.  
  40.         }
  41.         public void StartListen()
  42.         {
  43.  
  44.  
  45.             try
  46.             {
  47.                 NameValueCollection collection1 = ConfigurationSettings.AppSettings;
  48.                 m_mainSocket = new Socket(AddressFamily.InterNetwork,
  49.                                           SocketType.Stream,
  50.                                           ProtocolType.Tcp);
  51.                 IPAddress ip;
  52.  
  53.                 string ipstr = "198.158.0.20";
  54.  
  55.                 ip = IPAddress.Parse(ipstr);
  56.  
  57.                 IPEndPoint ipLocal = new IPEndPoint(ip, 7030);
  58.                 m_mainSocket.Bind(ipLocal);
  59.                 m_mainSocket.Listen(100);
  60.  
  61.                // Create the call back for any client connections...
  62.  
  63.  
  64.                 while (true)
  65.                 {
  66.                     m_mainSocket.BeginAccept(new AsyncCallback(OnClientConnect), null);
  67.                     Thread.Sleep(1000);
  68.                 }
  69.  
  70.             }
  71.             catch (Exception e1)
  72.             {
  73.                 Console.WriteLine(e1.Message.ToString());
  74.                 WriteErrorLogMessage(e1.Message);
  75.  
  76.  
  77.             }
  78.         }
  79.  
  80.  
  81.         public void OnClientConnect(IAsyncResult asyn)
  82.         {
  83.             try
  84.             {
  85.                Socket msocket;
  86.                 msocket = m_mainSocket.EndAccept(asyn);
  87.                 msocket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.KeepAlive, 1);
  88.                 msocket.IOControl(IOControlCode.KeepAliveValues, inValue, outvalue);
  89.                WaitForData(msocket);
  90.             }
  91.  
  92.             catch (Exception e1)
  93.             {
  94.                 Console.WriteLine(e1.Message.ToString());
  95.                 WriteErrorLogMessage(e1.Message);
  96.             }
  97.  
  98.         }
  99.  
  100.  
  101.         public void WaitForData(System.Net.Sockets.Socket soc)
  102.         {
  103.             try
  104.             {
  105.                 if (pfnWorkerCallBack == null)
  106.                 {
  107.                      pfnWorkerCallBack = new AsyncCallback(OnDataReceived);
  108.                 }
  109.  
  110.                 StateObject state = new StateObject();
  111.                 state.workSocket = soc;
  112.                 soc.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, pfnWorkerCallBack, state);
  113.  
  114.             }
  115.             catch (Exception e1)
  116.             {
  117.                 Console.WriteLine(e1.Message.ToString());
  118.                 WriteErrorLogMessage(e1.Message);
  119.             }
  120.  
  121.         }
  122.         public void OnDataReceived(IAsyncResult asyn)
  123.         {
  124.             Console.WriteLine("data received");
  125.             WriteLogMessage("data received");
  126.             bool socketClosed = false;
  127.             try
  128.             {
  129.                 StateObject stateobject = (StateObject)asyn.AsyncState;
  130.                 Socket sock = stateobject.workSocket;//assgning the app socket to new socket
  131.  
  132.                 int nBytesRec = sock.EndReceive(asyn);
  133.  
  134.                 if (nBytesRec > 0)
  135.                 {
  136.                     string sReceived = System.Text.Encoding.ASCII.GetString(stateobject.buffer, 0, StateObject.BufferSize);
  137.  
  138.                     sReceived = sReceived.TrimEnd('\0');
  139.                     WriteLogMessage(sReceived);
  140.                    if (sReceived != null && sReceived != " " && sReceived != "")
  141.                     {
  142.                        Console.WriteLine(sReceived);
  143.                 }
  144.  
  145.                 else
  146.                 {
  147.                     sock.Disconnect(false);
  148.                     sock.Close();
  149.                     stateobject = null;
  150.                     Console.WriteLine("Inside infinite loop");
  151.                     socketClosed = true;
  152.                  }
  153.                 if (!socketClosed)
  154.                 {
  155.                     byte[] Buffer = new byte[StateObject.BufferSize];
  156.  
  157.                     stateobject.buffer = Buffer;
  158.  
  159.                     sock.BeginReceive(stateobject.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(OnDataReceived), stateobject);
  160.                 }
  161.             }
  162.  
  163.             catch (SocketException e1)
  164.             {
  165.                 Console.WriteLine(e1.Message.ToString());
  166.                 WriteErrorLogMessage(e1.Message);
  167.             }
  168.  
  169.  
  170.             catch (Exception e1)
  171.             {
  172.                 Console.WriteLine("Inside infinite loop");
  173.                 WriteErrorLogMessage(e1.Message);
  174.             }
  175.         }

There is an underlined code, where we want to disconnect those socket connections which does not carry any value. When we did that what happens is, whenever the socket reconnects it does not connect, nor does any other live socket connects.


Please let me know where are we going wrong
Thanks in advance
Regards
cmrhema
Aug 7 '08 #1
0 1289

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: Corne Oosthuizen | last post by:
I'm writing a Telnet Server application using Asynchronous sockets. I spawn a listener thread to handel incomming connections and create a separate client socket for each new connection. I...
0
by: Darren Thomas | last post by:
Dear all, I have written a TCP server as a windows service that accepts connections using the System.Net.Sockets.Socket class. I use the various asynchronous methods in the socket class. I'm...
7
by: Colin | last post by:
I'm writing a little console socket server but I'm having some difficulty. Can I ask your advice - where is the best place to get some help on that topic? It would be nice if some people who knew...
4
by: taskswap | last post by:
I have a legacy application written in C that I'm trying to convert to C#. It processes a very large amount of data from many clients (actually, upstream servers - this is a mux) simultaneously. ...
4
by: Macca | last post by:
I am writing an application that uses asynchronous sockets to get data over ethernet from embedded devices, up to 30 concurrent devices.(These devices are written in C). My application...
2
by: Macca | last post by:
My app has an asynchronous socket server. It will have 20 clients connected to the server. Each client sends data every 500 millisecondsThe Connections once established will not be closed unless...
0
by: Macca | last post by:
Hi, I am writing an asychronous socket server to handle 20+ simulataneous connections. I have used the example in MSDN as a base. The code is shown at end of question. Each connection has a...
4
by: Engineerik | last post by:
I am trying to create a socket server which will listen for connections from multiple clients and call subroutines in a Fortran DLL and pass the results back to the client. The asynchronous socket...
6
by: Pat B | last post by:
Hi, I'm writing my own implementation of the Gnutella P2P protocol using C#. I have implemented it using BeginReceive and EndReceive calls so as not to block when waiting for data from the...
1
by: keksy | last post by:
Hi every1, I am writing a small client/server application and in it I want to send an image asynchronous from the client to the server through a TCP socket. I found an example code on the MSDN...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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...
0
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,...
0
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...

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.