Question

Threads in C++ Builder 6

Asked by: skiritis13

I was making a little app that acts as a server and i borrowed code from one I allready had, made on MFC though, that creates a thread that executes the server code. So, although everything (else) works, I wasn't able to find a function to replace AfxBeginThread() that executes a new thread in MFC.
I need to know how I can create threads in Builder.
Sorry if it's a newbie question, i just got into Borland Builder.
Thanx 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
2005-03-10 at 12:42:09ID21346071
Tags

builder

,

thread

Topic

C++ Builder

Participating Experts
2
Points
200
Comments
5

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. MFC and C++ builder
    How to use (incorporate) MFC with Borland C++ Builder?
  2. Borland Builder and TrayIcon
    How can i use TrayIcons in my Borland Builder App ? Is there an example code or Builder Component ?
  3. Client Threads with Borland Builder
    Im looking for a tutorial on writing client threads using Borland C++ Builder 5. Ive already read the help included, which is pretty decent, however, Im still having problems even though I follow the steps recommended (specifically with inability to acces variables from my fo...
  4. Using Threads in Borland C++ builder for Winmdows Appli…
    Hi I have created a simple form application in Borland C++ builder 6 and wish to use threads with my application. I have got a thread working without much problem but I wish to use a variable previously declared in the header of my form within the thread. i.e I want to pass ...

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: gtokasPosted on 2005-03-10 at 13:29:13ID: 13511062

Hello there...
Server?? What kind??
If it is TCP/IP then:
Drop a TServerSocket at your form(Internet tab)...
By default the connection type is nonblocking...
THAT MEANS each connection to the socket executed at its own thread...

Those are for your information...
It is a bit different than MFC... Anyway those sockets at the internet tab are wrappers around winsock... They handle MOST of your needs ...

One more thing.. At BCB\Examples\Internet you will find an example called chat...
Explore it and feel free to post again if you have questions...

gtokas.

 

by: kode99Posted on 2005-03-10 at 13:45:21ID: 13511235

Lucky for you threads are quite simple in Builder.  Just create a descendant from the TThread class by writing a Execute method.  CBuilder will make the basic file for you from File->New,  New Tab at the bottom - Thread Object.

The CBuilder helpfile is quite useful as well.  Look under 'TThread' and also 'Using TThread'
Borland Example files in the Borland  ..\Borland\CBuilder5\Examples\Apps\Threads area.

Heres a small tutorial
http://www.temporaldoorway.com/programming/cbuilder/threads/basics.htm

Another basic thread example
http://cc.borland.com/ccweb.exe/listing?id=21393

To get this one to work just make a new project and stick in Unit1 and Unit2.  It has a project but it is more work to clean it up to compile and run.  Unit2 is a very basic TThread class example and Unit1 is a GUI frontend to start and stop the threads.

Also chapter 7 of the Developers guide (that came with my CBuilder5) covers threads - not sure if v6 also has the book.  I think there is a chapter in the CBuilder 5 or 6 Developers Guides as well.  Useful books in any case.

As gtokas mentions there may be some components that do most of the thread management work for you depending on what you are doing.  eg most internet servers.

 

by: skiritis13Posted on 2005-03-14 at 06:04:28ID: 13534889

thanx kode99 for the thread links but since i can make a tcpip server using ready components i think i'll go that way for now.
gtokas can you simply tell me how reading and writing works between the server and the client compo?
I understand that the moment the client connects the onwrite function is called.
I use client->Socket->SendBuf(buffer,sizeof(buffer)) inside the OnWrite func to send to the server.
Is this correct?
Simply put, I try sending a file via a 512byte buffer like that:

        do {
                memset(buffer,0,sizeof(buffer));

                bytes_read += fread( buffer, sizeof(BYTE), sizeof(buffer), source );

                client->Socket->SendBuf(buffer,strlen(buffer));

                progress->StepBy(file_size/(bytes_read+1));
        }
        while( feof(source) == 0 );

this code exists inside OnWrite;
Am doing the write thing?

On the other side, at the server's OnClientRead func i have:

        int rec;
        do {
                memset(buffer,0,sizeof(buffer));

                rec = server->Socket->ReceiveBuf(buffer,sizeof(buffer));

                fwrite( buffer, sizeof(BYTE), strlen(buffer), dest );
        }
        while(rec>0);

and to tell you the truth I do not know what the ReceiveBuf func returns since the builder's help is not very thorough. I assume that it returns the bytes that it read.

thanx for any xtra help on this...

 

by: gtokasPosted on 2005-03-15 at 04:24:05ID: 13543647

Check out this:
Its an example I downloaded and helped me some years ago...

The header:
//---------------------------------------------------------------------------
#ifndef Unit1H
#define Unit1H
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <ScktComp.hpp>
#include <ExtCtrls.hpp>
//---------------------------------------------------------------------------
class TForm1 : public TForm
{
__published:      // IDE-managed Components
    TServerSocket *Server;
    TMemo *Memo1;
    TButton *cmdClose;
    TTimer *Timer1;
    TLabel *Label1;
    TLabel *Label2;
    TLabel *Label3;
    TBevel *Bevel1;
    TButton *Button1;
    TEdit *Edit1;
    TLabel *Label4;
    TEdit *txtPort;
    TButton *cmdChangePort;
    void __fastcall cmdCloseClick(TObject *Sender);
    void __fastcall ServerAccept(TObject *Sender,
          TCustomWinSocket *Socket);
    void __fastcall ServerClientDisconnect(TObject *Sender,
          TCustomWinSocket *Socket);
    void __fastcall ServerClientError(TObject *Sender,
          TCustomWinSocket *Socket, TErrorEvent ErrorEvent,
          int &ErrorCode);
    void __fastcall ServerClientRead(TObject *Sender,
          TCustomWinSocket *Socket);
    void __fastcall ServerClientWrite(TObject *Sender,
          TCustomWinSocket *Socket);
    void __fastcall ServerGetSocket(TObject *Sender, int Socket,
          TServerClientWinSocket *&ClientSocket);
    void __fastcall ServerListen(TObject *Sender,
          TCustomWinSocket *Socket);
    void __fastcall FormActivate(TObject *Sender);
    void __fastcall ServerGetThread(TObject *Sender,
          TServerClientWinSocket *ClientSocket,
          TServerClientThread *&SocketThread);
    void __fastcall ServerThreadStart(TObject *Sender,
          TServerClientThread *Thread);
    void __fastcall ServerThreadEnd(TObject *Sender,
          TServerClientThread *Thread);
    void __fastcall Timer1Timer(TObject *Sender);
    void __fastcall Button1Click(TObject *Sender);
    void __fastcall ServerClientConnect(TObject *Sender,
          TCustomWinSocket *Socket);
    void __fastcall cmdChangePortClick(TObject *Sender);

private:      // User declarations
public:            // User declarations
    __fastcall TForm1(TComponent* Owner);
};
//---------------------------------------------------------------------------
extern PACKAGE TForm1 *Form1;
//---------------------------------------------------------------------------
#endif

Source File:
/*******************************************************
This is an example of how to set up a server listening
to incomming Telnet connections. I've tried to make it
as well structured as possible with the possibility to,
without any major modifications, build up a fully
functional telnet server for whatever use there might be.
I have commented it heavily, but if there still are any
questions (or suggestions) mail them to karlpest@home.se

Please visit KTRK's webpage at http://www.ktrk.net or
http://ktrk.tripod.com

Coded by Karl Tillstr&#966;m 2000-10-11

*******************************************************/

//---------------------------------------------------------------------------
#include <vcl.h>
#pragma hdrstop

#include "Unit1.h"

//---------------------------------------------------------------------------
#pragma package(smart_init)
#pragma resource "*.dfm"
TForm1 *Form1;



const Max_Connections = 30;  //Set how many sockets you wish to have open

struct Connected_User
{
    int SocketHandle;   //The Socket the user is connected to
    AnsiString Name;    //If you want to attatch a name to the user
    AnsiString Data;    //To get whole lines (look into ClientRead())
    AnsiString IP;      //The clients IP
    //Add more if needed, like TimeOut, PasswordAccepted, AccessLevel etc...
};

Connected_User User[Max_Connections];   //Handles the connected users
int ConnectionCount;    //Index used by User[]

void RemoveUser(TCustomWinSocket *Socket);      //Removes a user from a socket
int GetConnectionNo(int SocketHandle);  //Finds which User[] that represents the SocketHandle
void ClearUser(int SocketHandle);   //Clears the User[] for the specific user
void BroadCastMessage(AnsiString Message, int SkipUser);  //Use this to send a message to all connected users except SkipUser (SocketHandle)

//---------------------------------------------------------------------------
__fastcall TForm1::TForm1(TComponent* Owner)
    : TForm(Owner)
{

}
//---------------------------------------------------------------------------

void __fastcall TForm1::cmdCloseClick(TObject *Sender)
{
//Closes the Server Socket
Server->Active = false;
Memo1->Lines->Add("Server shut down!");
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ServerAccept(TObject *Sender,
      TCustomWinSocket *Socket)
{
if (Server->Socket->ActiveConnections-1  == Max_Connections)
    {
        //The server is full!
        Socket->SendText("Too many users!");
        Memo1->Lines->Add("OnAccept: Too many users");
        delete Socket;  //Free memory
        return;
    }



while (User[ConnectionCount].SocketHandle)    //Find free entrypoint
{
    ConnectionCount++;  //Unique indexes for the Connected users!
    if (ConnectionCount > Max_Connections)
        {
            ConnectionCount = 0;
        }
}

//Attatches the SocketHandle to the User[] in use
User[ConnectionCount].SocketHandle = Socket->SocketHandle;
//This is not how it's done when you are really naming the users
User[ConnectionCount].Name = "Guest" + IntToStr(Socket->SocketHandle);
Memo1->Lines->Add("OnAccept");



User[ConnectionCount].IP = Socket->RemoteAddress;
Memo1->Lines->Add(User[ConnectionCount].IP + " connected!");


}
//---------------------------------------------------------------------------


void __fastcall TForm1::ServerClientDisconnect(TObject *Sender,
      TCustomWinSocket *Socket)
{

ClearUser(Socket->SocketHandle);
Memo1->Lines->Add("ClientDisconnected " + IntToStr(Socket->SocketHandle));
//delete Socket;  //free memory (dunno if it's needed here...)
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerClientError(TObject *Sender,
      TCustomWinSocket *Socket, TErrorEvent ErrorEvent, int &ErrorCode)
{

switch (ErrorCode)
{
    case 10054 :
        //Client closed the connection
        RemoveUser(Socket);   //Removes the user
        Memo1->Lines->Add("Client closed connection");
        break;
    //add more error handlers as they are needed (e.g case <ErrorCode>)
    default :
        RemoveUser(Socket);
}

ErrorCode = 0;  //Prevents an error raise
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerClientRead(TObject *Sender,
      TCustomWinSocket *Socket)
{
//Occurs when a connected user sends some text to the server!

AnsiString Data = Socket->ReceiveText();    //Get the sent data!
int UserNo = GetConnectionNo(Socket->SocketHandle); //Finds out who sent it
if (UserNo == -1)
{
    //This shouldn't happen ever, but if it does you'll at least know about it
    ShowMessage("User cannot be found!");
    return;
}

/* Telnet users doesn't send complete lines at once,
therefore this will store all data in a temporary
AnsiString until a CRLF is received (\r\n)*/

User[UserNo].Data += Data;
if (User[UserNo].Data.AnsiPos("\r\n") == 0)
{
    //Not a complete line sent!
    return;
}
else
{
    //A complete Line sent!
    //SubString removes the ending CRLF ("\n\r") since we don't want them when we Parse out data!
    Memo1->Lines->Add("<" + User[UserNo].Name + "> " + User[UserNo].Data.SubString(1, User[UserNo].Data.Length() -2));
    //An example of how to use the BroadCastMessage function
    BroadCastMessage(User[UserNo].Data.SubString(1, User[UserNo].Data.Length() -2), Socket->SocketHandle);
    User[UserNo].Data = "";
}
       
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerClientWrite(TObject *Sender,
      TCustomWinSocket *Socket)
{
        Memo1->Lines->Add("ClientWrite");

}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerGetSocket(TObject *Sender, int Socket,
      TServerClientWinSocket *&ClientSocket)
{
    //GetSocket is the Socket->SocketHandle
    Memo1->Lines->Add("GetSocket " + IntToStr(Socket));
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerListen(TObject *Sender,
      TCustomWinSocket *Socket)
{
Memo1->Lines->Add("Listens on Port: " + IntToStr(Server->Port));

}
//---------------------------------------------------------------------------
void __fastcall TForm1::FormActivate(TObject *Sender)
{
//Opens the server (e.g Makes the server start Listening)
//Server->Active = true;

ConnectionCount = 1;    //Start counting on 1
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerGetThread(TObject *Sender,
      TServerClientWinSocket *ClientSocket,
      TServerClientThread *&SocketThread)
{
Memo1->Lines->Add("GetThread");
}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerThreadStart(TObject *Sender,
      TServerClientThread *Thread)
{
Memo1->Lines->Add("OnThreadStart");

}
//---------------------------------------------------------------------------
void __fastcall TForm1::ServerThreadEnd(TObject *Sender,
      TServerClientThread *Thread)
{
Memo1->Lines->Add("OnThreadEnd");
}
//---------------------------------------------------------------------------
void __fastcall TForm1::Timer1Timer(TObject *Sender)
{
    //Updates the current # of connections
    Label1->Caption = IntToStr(Server->Socket->ActiveConnections) + "/" + IntToStr(Max_Connections);
}
//---------------------------------------------------------------------------

void ClearUser(int SocketHandle)
{
//Use this when a user gets disconnected for whatever reason
int UserNo = GetConnectionNo(SocketHandle);
if (UserNo == -1) return;

/*Don't forget to update this section is you add more stuff to the User struct!*/
    User[UserNo].SocketHandle = 0;
    User[UserNo].Name = "";
    User[UserNo].Data = "";
    User[UserNo].IP = "";
/*_____________________________________________________________________________*/
}
//---------------------------------------------------------------------------

int GetConnectionNo(int SocketHandle)
{
//Retrieves which connection that represents the SocketHandle in question
for (int i=0; i<Max_Connections; i++)
{
    if (User[i].SocketHandle == SocketHandle) return i;
}
return -1;
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
//Activates the Server socket (e.g Starts to listen)
Memo1->Lines->Add("Server started!");
Server->Open();
}
//---------------------------------------------------------------------------

void __fastcall TForm1::ServerClientConnect(TObject *Sender,
      TCustomWinSocket *Socket)
{
Memo1->Lines->Add("connect");

}
//---------------------------------------------------------------------------

void BroadCastMessage(AnsiString Message, int SkipUser)
{

//Loops through the Socket->Connections array and sends the message to all users but SkipUser
//(You don't always want to broadcast the message to the user who sent it!)
//If you want to send to all the users including the one who sent it, call the function with SkipUser = -1 or something

for (int i=0;i<(Form1->Server->Socket->ActiveConnections); i++)
{
    if (Form1->Server->Socket->Connections[i]->SocketHandle == SkipUser)
    {
        // NOP
    }
    else
    {
        Form1->Server->Socket->Connections[i]->SendText(Message + AnsiString("\r\n"));
    }

}
}

void RemoveUser(TCustomWinSocket *Socket)
{
/*Clears the User[] and removes the Socket instance*/
    Form1->Memo1->Lines->Add("User " + User[GetConnectionNo(Socket->SocketHandle)].Name + " removed!");
    ClearUser(Socket->SocketHandle);
    delete Socket;

/*_________________________________*/
}
void __fastcall TForm1::cmdChangePortClick(TObject *Sender)
{
if (Server->Active == true)
{

 if (Application->MessageBox("Server must be shut down in order to change Listening port! \n Do you wish to continue?", "Temporarily shut down server?", MB_OKCANCEL + MB_DEFBUTTON1) == IDCANCEL)
   return;

    //Server must be shut down to be able to change port!
    cmdClose->Click();
    Server->Port = StrToInt(txtPort->Text);
    Memo1->Lines->Add("Listening port changed to " + txtPort->Text);
    Button1->Click();
}
else
{
    Server->Port = StrToInt(txtPort->Text);
        Memo1->Lines->Add("Listening port changed to " + txtPort->Text);
}

}
//---------------------------------------------------------------------------

 

by: gtokasPosted on 2005-03-17 at 09:37:36ID: 13567273

Skiritis13,
Was the example helpfull???
Did you found your way using the Borland's ways??
A reply will be appreciated...

gtokas.

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...