Jump to content


Check out our Community Blogs

nick3

Member Since 20 Feb 2009
Offline Last Active May 21 2013 09:17 PM
-----

Topics I've Started

Send function in SocketAsyncEventArgs

04 September 2012 - 04:01 AM

Hello, I'm working on a Client/Server application and using the SocketAsyncEventArgs class. I can send a message from the Client and I can receive with the server (and answer directly), but I can't send "at will" from the server. Here is some code that I created for send, is there anyone that can see my error? If you look at the code below, everything looks fine in my handleSend (the message looks right and t.Connection.SendAsync(completeArgs); is called, but nothing shows up on the Client side... (Except for the direct answer I get...)


SERVER CODE:

internal SocketListener(Int32 numConnections, Int32 bufferSize, Service1 parent)
{
try
{
 this.parent = parent;
	
 this.todo = new ArrayList();
 this.tokenPool = new ArrayList();
 this.numConnectedSockets = 0;
 this.numConnections = numConnections;
 this.bufferSize = bufferSize;
 this.readWritePool = new SocketAsyncEventArgsPool(numConnections);
 this.semaphoreAcceptedClients = new Semaphore(numConnections, numConnections);
		
 for (Int32 i = 0; i < this.numConnections; i++)
 {
  SocketAsyncEventArgs readWriteEventArg = new SocketAsyncEventArgs();
  readWriteEventArg.Completed += new EventHandler<SocketAsyncEventArgs> (OnIOCompleted);
 
  readWriteEventArg.SetBuffer(new Byte[this.bufferSize], 0, this.bufferSize);
		
  this.readWritePool.Push(readWriteEventArg);
 }
  Thread t = new Thread(handleSend);
  t.Start();
 }
 catch (Exception e)
 {
 }
}


public void handleSend()
{
 try
 {
 foreach (Token t in tokenPool)
  {
  if (t.ID != "" && t.ID != null)
   {
   if (parent.cStructHandler.gotMsg(t.ID))
    {
     MsgStruct tmpCs = parent.cStructHandler.getNextMsg(t.ID);
     if (tmpCs.getMsg().Length != 0)
     {
      byte[] ba = Encoding.UTF8.GetBytes(tmpCs.getMsg());
      if (tmpCs.getCrc() == "")
      {
       ulong tmp = CRC.calc_crc(ba, ba.Length);
       tmpCs.setCrc(tmp.ToString("X"));
      }
      if (tmpCs.canSendByTimeout())
      {
       string crcStr = "?" + tmpCs.getCrc() + "?";
       byte[] bb = Encoding.UTF8.GetBytes(crcStr);
       crcStr = Encoding.UTF8.GetString(bb);
       byte[] fullMsg = new byte[ba.Length + bb.Length];
       bb[0] = 254;
       bb[bb.Length - 1] = 255;
       ba.CopyTo(fullMsg, 0);
       bb.CopyTo(fullMsg, ba.Length);
       SocketAsyncEventArgs completeArgs = new SocketAsyncEventArgs();
       completeArgs.SetBuffer(fullMsg, 0, fullMsg.Length);
       completeArgs.UserToken = t;
       completeArgs.RemoteEndPoint = t.Connection.RemoteEndPoint;
       completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted);
       t.Connection.SendAsync(completeArgs);
      }
     }
    }
   }
  }

  Thread.Sleep(500);
  handleSend();
 }
 catch (Exception e)
 {
 }
}



CLIENT CODE:


private void OnReceive(object sender, SocketAsyncEventArgs e)
{
 Console.WriteLine("\nOnReceive: " +  System.Text.UTF8Encoding.ASCII.GetString(e.Buffer) + "\n");

 autoSendReceiveEvents[SendOperation].Set();
}
private void OnSend(object sender, SocketAsyncEventArgs e)
{
 // Signals the end of send.
 autoSendReceiveEvents[ReceiveOperation].Set();
 if (e.SocketError == SocketError.Success)
 {
  if (e.LastOperation == SocketAsyncOperation.Send)
  {
  
   Socket s = e.UserToken as Socket;
   byte[] receiveBuffer = new byte[255];
   e.SetBuffer(receiveBuffer, 0, receiveBuffer.Length);
   e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive);
   s.ReceiveAsync(e);
  }
 }
 else
 {
  this.ProcessError(e);
 }
}
public void sendloop()
{
 try
 {
  byte[] data = new byte[1024];
  string input, stringData;
			
           
  bool gotData = true;
  lastTime = DateTime.Now;
  String bilId = ini.GetFromIni("CONFIG", "BIL");
  MsgStruct hello = new MsgStruct("I;1;" + bilId);
                         
  while (gotData)
  {
   try
   {
    this.parent.isConnected = true;
    DateTime tmpDate = lastTime.AddSeconds(30);
    if (DateTime.Now > tmpDate)
    {
						
      gotData = false;
     }
     tmpDate = lastTime.AddSeconds(13);
     if (sendPing && DateTime.Now > tmpDate)
     {
       MsgStruct ping = new MsgStruct("X;" + DateTime.Now.ToLongTimeString() + ";" + Convert.ToString(this.parent.carPos.Y) + ";" + Convert.ToString(this.parent.carPos.X));
       ping.setAckNeeded(true);
       buffert.Add(ping);
       sendPing = false;
      }
      while (true)
      {
        if (canUseBuffert)
        {
          canUseBuffert = false;
          if (buffert.Count > 0)
          {
           if (buffert[0] != null && buffert[0].getMsg().Length != 0)
           {
              byte[] ba = Encoding.UTF8.GetBytes(buffert[0].getMsg());
              if (buffert[0].getCrc() == "")
              {
                ulong tmp = CRC.calc_crc(ba, ba.Length);
                buffert[0].setCrc(tmp.ToString("X"));
               }
               if (buffert[0].canSendByTimeout())
               {
                string crcStr = "?" + buffert[0].getCrc() + "?";
                byte[] bb = Encoding.UTF8.GetBytes(crcStr);
                crcStr = Encoding.UTF8.GetString(bb);
                byte[] fullMsg = new byte[ba.Length + bb.Length];
                bb[0] = 254;
                bb[bb.Length - 1] = 255;
                ba.CopyTo(fullMsg, 0);
                bb.CopyTo(fullMsg, ba.Length);
                string s = System.Text.UTF8Encoding.ASCII.GetString(fullMsg);
                                       
                if(buffert[0].getMsg()[0] != 'X')
                                             
									
               SocketAsyncEventArgs completeArgs = new SocketAsyncEventArgs();
               completeArgs.SetBuffer(fullMsg, 0, fullMsg.Length);
               completeArgs.UserToken = this.clientSocket;
               completeArgs.RemoteEndPoint = this.hostEndPoint;
               completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend);
               clientSocket.SendAsync(completeArgs);
									
               AutoResetEvent.WaitAll(autoSendReceiveEvents);
                                 
               Console.WriteLine( Encoding.ASCII.GetString(completeArgs.Buffer, completeArgs.Offset, completeArgs.BytesTransferred));
		
               if (!buffert[0].isAckNeeded())
                buffert.Remove(buffert[0]);

										
              }
             }
            }
            canUseBuffert = true;
            break;
           }
          }
         }
         catch (Exception e)
         {
         }
        }
        Console.WriteLine("Disconnecting from server...");
       }
       catch (Exception e)
       {
        canUseBuffert = true;
       }
	 }

Remove Sleep in C# multithread application

31 August 2012 - 02:45 AM

Hello,

I have a question about Threads, I got a multithread TCP accplication that have connections with multiple clients. The threads have operations that take quite long. (maybe a minute or so).. I have now realised that Sleeps is NOT the way to go, but im not sure how to do it right. Anyone that has any ideas? Here is my code, at the moment Every Client object has a Thread that recievies and sends messages and a thread that handle the Tasks that should be handled (depending on the messages)... (for example creates and answer that the msg threads sends). But im not very happy with this.

Would love some help or hints!

/Nick



//Waiting for TCP-connections and creating them as they arrive. Starts a Thread that handles the messages recieved and sent with this thread.
private void ListenForClients()
{
	 try
	 {
		 this.tcpListener.Start();
		 while (true)
		 {
			 TcpClient client = this.tcpListener.AcceptTcpClient();
			 Connection c = new Connection(this.parent);
			 connectionCollection.Add(c);
			 Thread clientThread = new Thread(new ParameterizedThreadStart(c.HandleClientComm));
			 threadCollection.Add(clientThread);
			 clientThread.Start(client);
		 }
	 }
	 catch (Exception e)
	 {
	 }
}
//Connection constructor, creates a ToDo-thread, this handles the messages (DB, Filewriting etc.) recieived and creats new ones to be sent.
public Connection()
{
	 this.todo = new ArrayList();
	 todoT = new Thread(handleToDo);
	 todoT.Start();
}

//Messagehandeling
public void HandleClientComm(object client)
{
	 try
	 {
		 TcpClient server = (TcpClient)client;
		 NetworkStream ns = server.GetStream();
		 byte[] data = new byte[1024];
		 string input, stringData;
		 online = true;
		 DateTime lastTime = DateTime.Now;
		 while (true && this.online)
		 {
			 try
			 {
				 if (lastTime.AddMinutes(2) < DateTime.Now)
					 break;
				 data = new byte[1024];
				 if (ns.DataAvailable && ns.CanRead)
				 {
					 int recv = ns.Read(data, 0, data.Length);
					 if (recv > 0)
					 {
						 lastTime = DateTime.Now;
						 if ((byte)data[recv - 1] == (byte)255)
						 {
							 int cnt = -1;
							 for (int i = 0; i < recv; i++)
							 {
								 if (data[i] == (byte)254)
								 {
									 cnt = i;
									 break;
								 }
							 }
							 int nr = recv - cnt - 2;
							 byte[] tmp = new byte[nr];
							 for (int i = 0; i < nr; i++)
							 {
								 tmp[i] = data[cnt + i + 1];
							 }
							 string crc = Encoding.UTF8.GetString(tmp);
							 stringData = Encoding.UTF8.GetString(data, 0, cnt);
							 MsgStruct msgs = new MsgStruct(stringData);
							 msgs.setCrc(crc);
							 Thread.Sleep(200);
							 addTodo(msgs);
							 if (msgs.getMsg()[0] == 'T' && this.type == 1)
								 this.parent.cStructHandler.sendAck(msgs, this.ID);
							 Console.WriteLine(todo.Count);
						 }
					 }
				 }
				 if (parent.cStructHandler.gotMsg(this.ID))
				 {
					 MsgStruct tmpCs = parent.cStructHandler.getNextMsg(this.ID);
					 if (tmpCs.getMsg().Length != 0 && ns.CanWrite)
					 {
						 byte[] ba = Encoding.UTF8.GetBytes(tmpCs.getMsg());
						 if (tmpCs.getCrc() == "")
						 {
							 ulong tmp = CRC.calc_crc(ba, ba.Length);
							 tmpCs.setCrc(tmp.ToString("X"));
						 }
						 if (tmpCs.canSendByTimeout())
						 {
							 string crcStr = "?" + tmpCs.getCrc() + "?";
							 byte[] bb = Encoding.UTF8.GetBytes(crcStr);
							 crcStr = Encoding.UTF8.GetString(bb);
							 byte[] fullMsg = new byte[ba.Length + bb.Length];
							 bb[0] = 254;
							 bb[bb.Length - 1] = 255;
							 ba.CopyTo(fullMsg, 0);
							 bb.CopyTo(fullMsg, ba.Length);
							 string s = System.Text.UTF8Encoding.ASCII.GetString(fullMsg);
							 ns.Write(fullMsg, 0, fullMsg.Length);
							 Thread.Sleep(200);
							 if (!tmpCs.isAckNeeded())
								 parent.cStructHandler.removeNextMsg(this.ID);
						 }
					 }
				 }
				 Thread.Sleep(100);
			 }
			 catch (Exception e)
			 {
				 break;
			 }
		 }
		 ns.Close();
		 server.Close();
		 dead = true;
	 }
	 catch (Exception e)
	 {
		 dead = true;
	 }
}

//Todo Thread
public void handleToDo()
{
	 try
	 {
		 int cnt = 0;
		 while (true)
		 {
			 if (todo.Count > 0)
			 {
					 //SWITCH CASE FOR DIFFERENT MESSAGE TYPES, DOING TASKS DEPENDING ON WHAT ONES...
					 Thread.Sleep(100);
			 }
			 else
			 {
				 if (dead)
				 {
					 todoT.Abort();
					 todoT = null;
					 break;
				 }
			 }
			 Thread.Sleep(200);
		 }
	 }
}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download