Question

Syncronizing between INDY TCP servers

Asked by: pcsentinel

I have a complex project underway, but to simplify the question, imagine an application with 2 INDY TCP Server Controls

Each server is connected to a different client, that has a different function, (No I cannot use a single server for a number of reasons)

Server Connection 1 fulfills requests from its client and returns data to it, Server 2 besides fulfilling its own clients requests also needs to write to Server 1's clients

How do I ensure ( code sample please) that Server 2 does not try and send to Server 1's clients while Server 1 is processing a request from its client, i.e. how do I synchronize between the 2

thanks in advance

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2006-08-14 at 13:40:56ID21954114
Tags

indy

Topic

Delphi Programming

Participating Experts
2
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. Between FastNet and Indy
    Why most of experts here prefer to recomend Indy Net Components rather FastNet ? If FastNet is so bad why Borland still place it in D6 ? is it just for backward compatibility or what ? Again is FastNet component is that worst ? what thing make it so ? I'm in the midd...
  2. WEB PAGE WITH INDY
    WEB PAGE WITH INDY I want to set web page with indy v8. example : www.abcdefghijkl.com and when I start IE, I want that web page www.abcdefghijkl.com is shown. Thanks.
  3. Customizing TCommBlock (Indy)
    I've started playing with the TCP Chat demo in Indy. It uses CommBlock: TCommBlock with four variables; Msg, Command, MyUserName, ReceiverName. I need more than 4 blocks of information sent/received at one time. How can I modify those or create my own?
  4. [Sockets] Indy or ICS?
    I don't want to start a flame-war but I often hear people praising the ICS components here while I myself just prefer the Indy components. So, a challenge. Define in up to 2000 words why we should use package [X] instead of package [Y] when developing client/server components...
  5. HTTP indy &  proxy
    Hi , I am using an indy component IdHTTP. It works well when the proxy does not require authetication. however when the proxy requires authentication then it gives an exception - EIDHTTPprotocolexception HTTP/1.1 407 Proxy Authentication Required (ISA server requires...
  6. synchronize specific thread in indy idtcpServer
    Hello Experts! I have the following problem: A running IdTCPServer is handling requests. For this request indy starts an onExecute event and starts this procedure: procedure TForm1.IdTCPServerExecute(AThread: TIdPeerThread); Within this procedure I can easy do a s...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: Workshop_AlexPosted on 2006-08-14 at 14:01:48ID: 17313567

You would do that by assigning them to different ports. E.g. Server1 connects to port 80 and Server2 connects to port 81. Or whatever. If you use your own custom ports, pick some high values.

 

by: pcsentinelPosted on 2006-08-14 at 14:07:23ID: 17313603

Hi Alex, sorry not following you, yes both server controls use different ports, but the crux of the question is how do I ensure that Server 2 messages to Server 1's clients do not cause a corruption within server 1's own processing of its own clients requests

INDY 9 BTW

 

by: ciulyPosted on 2006-08-14 at 14:46:33ID: 17313887

wel, the easiest way that does work is to use the good old process sincronization mechanisms: semaphores, mutex, etc.
say using critical section (this is  my favorite :D ) it would look something like this (the flow):

server1.clientX.cs.enter;// this locs clientx processing for server1
server1.clientX.process
server2.clientX.cs.enter;// this starts to wait for the resource to be abailable
server1.clientX.process
server1.clientX.process
server1.clientX.cs.leave;// not server2 kicks in
server2.clientX.process
server2.clientX.process
server2.clientX.cs.leave// server2 now finishes with it

same goes the other way around: if server2 gets to clientx faster than server1, then server1 will wait for server2 to finish

same thing is valid for mutex and cemaphores and whatever. of course using critical section process wide is a little trickier, and network wide is even more trickier unless ... you can simulate the same thing for network processes.

how to do that? it si rather simple: you will use a 3rd server (application) which can be installed on any of the 2 PCs. this will be the control app.

so what do you do?
- sever3 listens on port X
- one of server 1 or 2 will block access to client Y by connecting to server 3 and issuing a lock on client Y
- after finishing, it will unlock teh client by issueing an unlock on client Y
- when server 3 receives a lock on client Y it will try to lock it. if it's locked, it waits. if it's not, it locks it. how? using one of the process synchronization mechanisms I mentioned above :) (now we are talking about one process with multiple threads (one per each connection/lock))

unfortunatly a test code is not that fast to write (though it's easy) and it's 12:41 AM here.
but I will tell you the basics and you'll see that the method works.

so, a server will use a blocking socket and do seomthing like this:

socket.write("lock client x");
socket.read();// this will block until server3 responds with OK
process client x
socket.write("unlock client x");

it's that simepl on the 2 server side (1 and 2)

now on server 3:
in the onconnect event:
- create a new thread that will lock client sent on socket

- the trhead will
- client := socket.read(); // parse client number or ID
- cs[client].enter // try locking the client using critical section array or dinamic list
- socket.write("ok");
- socket.read()// this should be unclock client x, but we can ignore this, because according to our locking protocol defined, this is the only thing we can get. however, we can use an assert on the data sent just to be on the safe side
- cs[client].leave

hope it looks ok to you :)

 

by: pcsentinelPosted on 2006-08-14 at 23:13:44ID: 17315883

ciuly, I think you are leading me in the right direction, however I cant put another server object on Client 1's program becauase I have no access to that program

Client one is polling the server so it already receives messages, but it seems it is loosing some or corrupting them because they are from differnet threads

to simplify matters imagine that I have a server app with just one tcp server. In this app there are 2 timers each firing at differnet intervals, when they fire I need to do a writeln to the client
both timers call the same bit of code , I have never used critical sections, but this looks like it could be the way, but how to implement?

procedure sendmsg(data: string);
begin
   TCPServer.Writeln(Data);
end;

presumably should change to

declare
  cs: TCriticalsection

procedure sendmsg(data: string);
begin
   if not Assigned(cs) then
    cs:=TCriticalSection.Create;
   cs.Acquire;
   TCPServer.Writeln(Data);
   cs.Release;
end;

procedure Timer1.OnTimer;
begin
  SendMsg('Something');
end;

procedure Timer2.OnTimer;
begin
  SendMsg('Something Else');
end;

Or is this wrong?

 

by: ciulyPosted on 2006-08-14 at 23:37:24ID: 17315988

first thing is first. you are making some confusion regardin servers and clients. you say quite often thet server connects. that is false. server does not connect. server waits/listens. only clients connect.
so .. you don't need to put a server on client1's machine. the server needs to be put where the 2 tcpserver components are located (either the same app, or the same pc)
servers have nothing to do with clients when it comes to location.

getting to the bottom of this:
- for that small piece of code, yes, the setup with CS would be something like you have done.
- now I understand that the 2 tcpservers are actually in the same application. if this is correct, you don't ened that thing with server3 I explained you above. you can go directly to use critical sections on the piece of code that needs to be sychronized.

but better explain in detail the setup of your environment (both servers and clients) and where and how and aproximatly when the problematic code is executed and maybe any other info I need to know and I'll explain you where and how you need to setup synchronization (if it's really needed:  I also think there might be an issue in your protocol or implementation of protocol)

 

by: pcsentinelPosted on 2006-08-15 at 00:25:11ID: 17316133

Ok will try

Main App has a number of TCPServer controls within it, these controls are connected to various clients, which I do not have control of

Client 1 sends a message to the server app, the server app acknoweldges receipt of that message, processes some data and then sends a reply to that client. Client 2 connects to a different TCPServer control within the same server app. This processes is own data, however it also needs to send data to Client 1.

So in pseudo

procedure TCPServer1.OnExecute;
begin
  TCPServer1.ReadLn;
  >>process data
  SendData1(Data);
end;

procedure TCPServer2.OnExecute;
begin
  TCPServer2.ReadLn;
  >>process data
  SendData2(Data);
  if x then
    SendData1(Data);
end;

prcoedure SendData1(Data: string);
begin
 TCPServer1.WriteLn(Data);
end;

prcoedure SendData2(Data: string);
begin
 TCPServer2.WriteLn(Data);
end;

 

by: Workshop_AlexPosted on 2006-08-15 at 00:38:52ID: 17316173

Thus, this 'sending messages to the wrong client' seems to be a non-issue to me... Each server listens to it's own port and will use that port to communicate with the client. But let me get the situation clear...

You have one server executable. In it there are two server components. Both listen to different ports. Now, first of all there is the question of how many clients can be connected to both server components. Because if you're going to use a critical section then every client request will delay the execution of other client requests. So let's start with a simple code example: (Server code!)

type
  TForm1 = class(TForm)
    IdTCPServer1: TIdTCPServer;
    procedure FormCreate(Sender: TObject);
    procedure FormDestroy(Sender: TObject);
    procedure IdTCPServer1Execute(AThread: TIdPeerThread);
    procedure IdTCPServer2Execute(AThread: TIdPeerThread);
  private
    CS: TCriticalSection;
  public
  end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  CS := TCriticalSection.Create;
end;

procedure TForm1.FormDestroy(Sender: TObject);
begin
  CS.Free;
end;

procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
begin
  CS.Enter;
  try
    Sleep(1000);
  finally CS.Release;
  end;
end;

procedure TForm1.IdTCPServer2Execute(AThread: TIdPeerThread);
begin
  CS.Enter;
  try
    Sleep(1000);
  finally CS.Release;
  end;
end;

If you use above code, however, you will have a big problem. As long as one of the two Execute methods is active, no other client requests will be processed and this will result in time-outs on very busy moments. (Or when the Execute performs some very slow code.) This is definitely NOT what you would like. Unless you only have one connected client...
Basically, what you would need is some indication that at least one thread is still active in it's execute method. For that a mutex would be a better solution. You would have something like this then:

const
  UniqueName = 'UniqueName';

procedure TForm1.IdTCPServer1Execute(AThread: TIdPeerThread);
var
  Mutex: THandle;
begin
  Mutex := CreateMutex(nil, false, UniqueName);
  try
    Sleep(1000);
  finally CloseHandle(Mutex);
  end;
end;

procedure TForm1.IdTCPServer2Execute(AThread: TIdPeerThread);
var
  Mutex: THandle;
begin
  CS.Enter;
  Mutex := CreateMutex(nil, false, UniqueName);
  try
    if (GetLastError = ERROR_ALREADY_EXISTS) then
    begin
      // Sorry, executing stuff now.
    end
    else
    begin
      Sleep(1000);
    end;
  finally CloseHandle(Mutex);
  end;
end;

Yet this approach has as disadvantage that Server2 will detect if one or more Execute methods of Server1 are running, yet it can't wait until they have all stopped processing. And when you want Server2 to send something back to all clients, you would need to prevent all Server1 clients from starting the Execute method. At least, until Server2 is done sending data. This will lead in even more synchronisation steps between the two server components. And it will make it extremely complex too.

So it seems to me that you might have to find an alternative approach. One solution might be the implementation of a stack, which stores the data from Server2 which must be sent to the clients of Server1. You would need a stack for every connected client, though. So when Server2 is executing, it puts the data that needs to be sent to thee Clients of Server1 to all the Client stacks. Then it's job is done. When Server1.execute is called, it checks the stack for the currently connected client and before (or after) it's regular actions it will send the data from the stack and remove it from the stack.
In that case, all you would need to synchronise is the access to the stack. Thus each client stack would need it's own critical section and two methods. (Say, Pop and Push.) The two methods just enter and leave the critical section when modifying the stack data.
The advantage of this is that you determine when data is sent to the client.

As an alternative solution, you could add a third server component. The clients who would connect to Server1 would then also have to connect to Server3. When Server2 needs to send data to the clients from Server1, it will send this data to the clients of Server3 instead. And Server3 will know what to do with it. This way you don't have one single TCP/IP stream which is used for two kinds of traffic...

 

by: ciulyPosted on 2006-08-15 at 00:43:57ID: 17316181

that looks ugly and with a high posibility of errors unless the communication protocol is correctly defined and applications follow it. (like in case of the ftp)

so, in your case, at any given time, the server app must know exactly which clients are connected to the 2 server sockets and exactly when client1 expects the data preocessed for client2.

this is so very full of possible errors. you definitly need a solid protocol defined and clients to follow exactly the protocol. and the protocol must support waiting for data and such.

is this a proprietary protocol? can you post it?

 

by: pcsentinelPosted on 2006-08-15 at 00:48:38ID: 17316198

Each server control only has 1 client attached

 

by: Workshop_AlexPosted on 2006-08-15 at 01:38:14ID: 17316336

Well, if you only have one client connected to each, it seems quite simple to me. The critical section would work in that case. But then a stack will  be a simpler solution. Server2 would be pushing data to the stack and Server1 will pop it from the stack again. And the popped data is then send to the client, every time the client is polling Server1 for data.

That would be my solution, at least. But with only one client for each server it's a simple solution. Once you start having more than one client then you'll be in trouble.

 

by: pcsentinelPosted on 2006-08-16 at 11:28:53ID: 17328494

Thanks for your comments guys, I appreciate the help

I now have code that sort of looks like he following

creator create;
begin
  FCS:=TCriticalSection.Create;
end;

procedure TCPServer1.Execute;
begin
  lz:=TCPServer1.ReadLn;
  --do stuff
  SendData(lp);
end;

procedure TCPServer2.Execute;
begin
  lz:=TCPServer2.ReadLn;
  --do stuff
  SendData(lp);
end;

procedure SendData(Data: string);
begin

end;



 

by: pcsentinelPosted on 2006-08-16 at 11:31:00ID: 17328509

Sorry ignore last (misshit)

Thanks for your comments guys, I appreciate the help

I now have code that sort of looks like he following

creator create;
begin
  FCS:=TCriticalSection.Create;
end;

procedure TCPServer1.Execute;
begin
  lz:=TCPServer1.ReadLn;
  --do stuff
  SendData(lp);
end;

procedure TCPServer2.Execute;
begin
  lz:=TCPServer2.ReadLn;
  --do stuff
  SendData(lp);
end;

procedure SendData(Data: string);
begin
  CS.Acquire;
  try
    TCPServer1.Writeln(Data);
  finally
    CS.Realease;
  end;
end;




Comments please

Am asl toying with idea of using stack, one key problem that I need to allow for is that the external client is using Winsock not Indy

 

by: ciulyPosted on 2006-08-16 at 12:27:13ID: 17328925

looks ok. but I still have some problem with the following possibilities (senddata called from servers):
1
2

or
2
1

will this behave correctly? because there is no way of telling which thread will get to senddata first.


>Am asl toying with idea of using stack, one key problem that I need to allow for is that the external
>client is using Winsock not Indy

that should not matter :)

 

by: Workshop_AlexPosted on 2006-08-17 at 01:05:41ID: 17332313

> >Am asl toying with idea of using stack, one key problem that I need to allow for is that the external
> >client is using Winsock not Indy

> that should not matter :)

Nope. Doesn't matter. All you need is a TList in case of raw data ot a TStringList in case of just strings or maybe just a dynamic array or the real old-fashioned way with using single-listed pointers. Plenty of options to build a stack. And all you need is the ability to push data on the stack from the second server and pop it out again by the first server.

For example, in case of a stringlist, (var stack: TStringList;) Server2.execute would do this:
  CS.Acquire;
  try
    Stack.Add(SomeData);
  finally
    CS.Realease;
  end;

And your Server1.Execute would do something like this:
  CS.Acquire;
  try
    while (Stack.Count > 0) do begin
      SendData(Stack[0]);
      Stack.Delete(0);
    end;
  finally
    CS.Realease;
  end;

Careful, untested code. But it shows the principle. Thus when Server2 gets any action it will push data on the stack. When Server1 gets action, it will just pop everything from the stack again and send it to the client.

Only drawback would be when you have multiple clients since only one client will receive the stuff Server2 wants to broadcast. But as you said, there is only one client connected to Server1.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...