Online Programmer, Resources for Programmers

Programming Ezine Issues 1-1 to 2-3

Free resources for programmers !

Click here to visit: www.onlineprogrammer.org

Programming Articles from Online Programmer Ezine

Programming Techniques:
How to make a new style CHM help file
 Run Windows application in background or as a service
Multi Thread Programming in C++ Builder and Delphi
 Run Windows Application as a Windows NT Service Program
Shutting down a Windows NT/2000 ( C++ Builder and Delphi )
Reviews:
Choosing between Borland Products
 BeOS, Powerful operating system with rich development tools for free
 Delphi and C++ Builder for "Linux" !

Web Programming:
Cgi and Cgi-bin , What are they ? A sample program
 Start with Perl CGI now! Part I - What's CGI and Hello world!

 Network Programming:
 Sending Broadcasts with VB and C++Builder App
 Small TCP/IP Hello server with VB 6.0
 Small TCP/IP Hello Client Software with VB 6.0
 TCP/IP Client/Server software on Unix and Linux (Hello Client)
 TCP/IP Client/Server software on Unix and Linux, Part II, Server Software

Archive of Ezine Articles

OnlineProgrammer Ezine Subscription
This ezine is a none profit publication for intermediate and new programmers. Currently it is published monthly.
- You will learn a new programming technique or topic every issue.
- You will have a new network and web programming lesson right in your mailbox.
- You will have access to unique Linux programming lesson each month.
- You will receive most important software and programming news each month.

Enter your email and click the button to subscribe:
Our website

* Linux Programming and Network Programming Clubs
These are places for network and linux programmers to speak about their experiences and problems. Joining is very simple.

* Job database for custom programmers
If you are a custom programmer in web design, network
programming, unix and linux programming or windows programming you can enter your profile in our job database.
People who need a programmer will be able to browse your profile and contact you. If you want to add your profile you can visit our site and submit your information.

* Programming Forums: If you have any question about
Delphi & CBuilder, Network Programming, Web Programming, Linux & Unix programming, VB, C++, C, VC++ you can ask it in our forums. Our site is for programmers. Visiting programmers will see your questions and if they answer your question you will receive an email notification.

Web Design in 7 days

Learn web design with this interesting Free ebook. Just download your copy and start studying. You can ask your questions from the author.

9100 Downloads by now !

Click here to download your copy !

Forums

Delphi & CBuilder

Network

Web

Linux & Unix

VB

C++, C, VC++
Resources
Programming Clubs
Linux Programming Club

Network
Programming Club
MCSD
Study Group
Your Articles
If you have an article that you want to publish it with your name in our site or our ezine please send it with email to: Ezine Editor

webmaster@onlineprogrammer.org


OnlineProgrammer - Ezine Archive

How to make a new style CHM help file
Date: | Oct 15 2000
Subject: | Online Programmer Ezine, Volume 1, No.1
Article: | How to make a new style CHM help file

Here we will see the steps you must follow to make a .chm
help file.

1-You must be able to make .html web pages as a prerequisite.
I n fact chm files are compiled HTML files. Each chm file
contains one or more html pages compiled in the form of a
single compressed file.

Chm files are Win98 and 2000 native help files. Therefore if
you double-click on them in Windows explorer they will be
automatically opened by windows.

Chm files are very small in comparison with other technologies,
is more suitable for long reading and are easier to search and
navigate.

For this purpose you must learn html web page design or simply
use software like MS-FrontPage etc to make html files.
There is a free "Html web design course" at LearningOnline
homepage. To enroll in this course go to:

           http://www.learnem.com

2- After designing help files in html format you must install
HTML Help Workshop software from Visual Studio 6.0 CD1. It is
in "Htmlhelp" directory on your CD. You can also find it on
Microsoft's website.

3- Install the software and run program.

4- Now you must make a new project  (File -> New).
Do not choose the box "convert winhelp project" and press next.
Then choose a directory for your help project and enter a name
for your help project and then press next again. If you have
made html files before starting this; you can show it to
program. In this way they will be included in your project.
Otherwise an empty project will be made and you must add help
pages after they are designed.

5-Now use the left toolbar buttons to add or remove topics
(help page items organized in separate html pages) to
project.

6- Now press compile from Up Toolbar. Your CHM help file will
be ready in seconds.

7-If you need more help or you have any questions about this
subject or any other programming subject you can ask your
questions in our Support and Programming Forums at

             http://www.learnem.com

8-You can also find Html Workshop on Microsoft website.

Home Index
© 2000 JGhostar Ltd and Online Programmer . All Rights Reserved


Choosing between Borland Products
Date: | Oct 15 2000
Subject: | Online Programmer Ezine, Volume 1, No.1
Article: | Choosing between Borland Products

What do you think about Borland Delphi and C++Builder . How
about different versions? Did Borland (Inprise) better in
new versions. In this short article I show you results of
my tests on these compilers. Tests are done on a Celeron 500
with 128MB RAM on a PC100 motherboard.

Test program contains VCL Objects, Thread, Loop and other
tests. I do not promise that these tests are 100% correct but
they are good to have a general seen of their quality and
changes from one version to another.

I have written Delphi and C++ Builder codes so that they are
as near as possible (line by line) to each other.

                   Win2000 Pro.  Win NT4Srv.   Win 98 Sec.    Code
C++ Builder 4     2008            2017              2198             409K
C++ Builder 5     1092            1100              1156             426K
Delphi 4              849              989               1072             343K
Delphi 5              2016            2020              2193             355K

* Higher numbers show better results (all compiled static.
Delphi and C++ builder programs are only recompiled using higher
Version )

Results show that Delphi 5 is very better than Delphi 4 but
newer version of C++ builder is very slow. Everyone understands
the need for a good C++ RAD environment but this one makes
very slow programs.

In other tests that I performed, C++Builder had bad results
in many cases. I personally do not use it for critical
purposes and big applications. C Builder console programs
were about 10-50 times slower than DOS version (I compiled
exact program with BC31 and C++Builder 4). Also I saw a lot
of bugs and errors in C++Builder 4 (I have not worked much
with C++Builder 5 when I write this).

Delphi is very better in these cases . So however I am
a C programmer (Unix, Linux, VC++ ) I prefer Delphi for
my RAD works .I will publish test results on other compilers
soon.

To see complete article on web go to:

       http://www.angelfire.com/nt/sarmadys/test1.html


Sending Broadcasts
Date: | Oct 15 2000
Subject: | Online Programmer Ezine, Volume 1, No.1
Article: | Sending Broadcasts with VB 6.0

Broadcasting is frequently used in local area networks.
If you want to send a message to all local computers you
can use broadcasts. Here we will discuss about broadcasting
on TCP/IP network protocol.

For example if you want to find a resource on network you can
send a broadcast to all computers. Then computer(s) that
contain that resource can answer to you.

You can find several applications for broadcasting. Just be
sure to use broadcasting whenever it is really needed.

To send broadcasts you use UDP protocol to send packets to IP
address 255.255.255.255 and you can choose any port that is
free on your computers.

Sending and receiving UDP broadcasts is very easy. You will
not need a connect session for UDP. You just send and receive
packets. Also packet size limitation is related to your
network devices but assume 256 bytes for maximum size of data
you send each time.

Below you see a sample program written in Visual Basic using
MSWinsock.ocx component. This component is the most stable socket
object I have seen until now. It is very easy to program sockets
with this object. I even prefer this object to native Delphi
and C++Builder socket objects (Borland, Net Master and Indy)
in that environments.

Private Sub Command1_Click()
On Local Error Resume Next
Dim str As Variant
str = CVar(Text1.Text)
Winsock1.RemoteHost = "255.255.255.255"
Winsock1.RemotePort = 20480
Winsock1.SendData str
End Sub

Private Sub Form_Load()
Winsock1.Bind 20480
End Sub

Private Sub Form_Unload(Cancel As Integer)
Winsock1.Close
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Winsock1.GetData str, vbString
Text2.Text = str
End Sub

Form contains a command button and two text boxes.

If you want to write in other environment there is a Broadcast
Page at this address:

http://www.angelfire.com/nt/sarmadys/page3.html


Multi Thread Programming in C++ Builder and Delphi
Date: | Nov 01 2000
Subject: | Online Programmer Ezine, Volume 1, No.2
Article: | Multi Thread Programming in C++ Builder and Delphi

Have you ever written programs that their GUI stops to
respond because a process blocks program execution in a point
in your code? (For example blocking sockets)

If so, you can solve this problem with multi thread
programming. Windows can run multiple paths in your program
at once. So you can do your blocking operations in one thread
and GUI operations in main thread.

They will run without interrupting each other. Example
program is written in C++ Builder but it can be ported to
Delphi with small changes.

But be careful. Running VCL GUI codes are not thread safe so
we must run them inside a Synchronize() function call. This
will run unsafe functions with threads in mind, so the result
is a safe code.

You can download both C++ Builder and Delphi source codes
from this address :

http://www.angelfire.com/nt/sarmadys/page3.html

and now the code ...

1- Create a normal project. Save Form1 unit as Unit1.

2- Add a new thread object (File->New->Thread Object.
Now save Thread unit as Unit2.

3- Unit1 code is : ( headers excluded )

#include "Unit1.h"
#include "Unit2.h"

TForm1 *Form1;

__fastcall TForm1::TForm1(TComponent* Owner)
: TForm(Owner)
{
}

void __fastcall TForm1::Button1Click(TObject *Sender)
{
TTestThread *MyThread=new TTestThread(False);
//false starts thread on creation , True will suspend it
}

4- Unit2 code is : ( headers excluded )

#include "Unit2.h"
#include "Unit1.h"
#include "stdio.h"

int gCounter;

__fastcall TTestThread::TTestThread(bool CreateSuspended)
: TThread(CreateSuspended)
{
}

void __fastcall TTestThread::Execute()
{
int j;
for(int i=0;i<100;i++)
{
Synchronize(UpdateTextBox);
Sleep(1000);
gCounter++;
}
}

void __fastcall TTestThread::UpdateTextBox()
{
char temp[10];
sprintf(temp,"%d",gCounter);
Form1->Edit1->Text=temp;
}

5- Now run program and test to see if main form stops to
respond to your actions. It will not !. If you use
Sleep function in main thread ( main form ) in a loop ,
Form1 will freeze. We used Sleep function in a separate
thread therefore form will not freeze anymore.

As you see writing multi thread programs in C++ Builder and
Delphi is very easy. But know that writing thread programs
needs enough care. You must write thread safe code in thread
units. You must also prepare yourself for unordinary errors.

I wish this article be useful for those with complicated
freezing programs !!!


BeOS, New powerful operating system with rich development tools for free
Date: | Nov 01 2000
Subject: | Online Programmer Ezine, Volume 1, No.2
Article: | BeOS, New powerful operating system with rich development tools for free

Recently I downloaded Free Personal Edition of BeOS
(Be Operating system). I also downloaded development tools.
In this short article I will try to introduce it to people
who have not worked with it yet.

There are two copies of Personal edition.One is for
installation under Linux operating system and the other for
installation under windows. After installation BeOS is not
much dependent to these operating systems. Professional
edition of BeOS even does not need these two environments
for it's operation. It will boot by itself like Unix or
windows. Personal edition uses these OS environments as a
base for its own file system that consists of only one file
500M in size.

It's why they call it an Operating system in a file. All
files and applications reside inside this file and make a
complete file system. Inside BeOS you do not even know that
it's just a file. As this file is 500M maximum size of
Personal edition File system is 500M. But do not worry.
BeOS mounts all main kinds of partitions easily.

For example it saw my fat16,fat32 and Linux ext2 file systems
and I was able to work with them like it's own file system.
I even installed a software on my fat32 partition.

I tried windows installation version. It was very quick and
straight. It took me less than 10 minutes to have it up. It
was a very beautiful and professional looking environment
with something like windows 2000. By the way it asked only
a few questions. Most important is that It is more than 4
times to 5 times faster than windows 2000 and windows 98.

As soon as you click on some icon it's running. I was very
surprised by it's speed. It's even faster than Linux X11
X window system with different window managers. It was really
stable too.

It was only after 20 seconds after the time I taught about
dialing my ISP that I was ready to press dial button. It
contains a lot of multimedia (11 apps) and internet (5 apps)
applications ready for running. It also contains a beautiful
internet browser.

I also downloaded a lot of software's from :

http://www.bebits.com and http://www.downloads.com .

They include about 400M of programming languages, IDEs and
tools and also internet, game and other entertainment
applications. As it seems they at Be.com has wanted this OS
to be a very powerful environment for internet, multimedia
and gaming purposes.

Programming kit includes network, game and windowing toolboxes.
You can download a Basic programming language with an IDE
like MS Visual basic.

I must confirm that BeOS contains some bugs and weaknesses but
it has done its first steps better than its successors.
I downloaded it and I will continue to use and develop
applications for it.

I wish it will be enough powerful and widely used very soon
because it worth's it. Go on ! you test it too.

Home of BeOS is Be corporation at :

http://www.be.com


Cgi and Cgi-bin , What are they ? A sample program
Date: | Nov 01 2000
Subject: | Online Programmer Ezine, Volume 1, No.2
Article: | Cgi and Cgi-bin , What are they ? A sample program

Cgi is a program that runs on a web server and produces html
web pages dynamically just before web server wants to send
it to you.

Web server is responsible for running Cgi program and
gathering its output results and forming it as a html page
and sending it to web browser over internet connection.

Cgi-bin programs can be written in almost every programming
environment that is able to produce console binary
executables.Cgi-bin programs produces html text and web
server sends resulting html. As pages are produced by a
program they can change dynamically. For example they can
contain search results on a database .

In the other side there are programming languages like
"Perl" that do not produce binary executables. Perl programs
run with Perl interpreter assistance. Same as cgi-bin these
programs make dynamic html pages. As they are not compiled
we call them "Cgi" programs .

Below you will see two sample programs in C. They will compile
to binary executables so they will produce cgi-bin programs.

First program is written for cc or gcc under Unix operating
system. You can run it under any Unix web server capable to
run Cgi programs. Under Unix you must be sure that Cgi program
has execution permission.

#include<stdio.h>
main()
{
printf("Content-type: text/html\n\n");
printf("<html><H1>Hello World!</H1></html>");
}

Second program is a Visual C++ console application that can
be run with IIS or any other windows web server.

#include "stdafx.h"
#include<stdio.h>
int APIENTRY WinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
printf("Content-type: text/html\n\n");
printf("<html><H1>Hello World!</H1></html>");
return 0;
}

If you have more questions about Cgi programs you can visit
our support forums and subscribe to our Cgi mailing list.

To visit our site go to :

http://learningonline.hypermart.net


Run Windows application in background or as a service
Date: | Dec 01 2000
Subject: | Online Programmer Ezine, Volume 1, No.2
Article: | Run Windows application in background or as a service

Sometimes we need an application to run every time we start
windows, even when user has not logged in. It is something
like service programs that run in background even if we do
not see them. In this article we will tell you how to do
this in windows 98 and 95. In next issue we will see how to
run an application as a service like other services in
windows NT and 2000.

You must be familiar with windows registry before you can
use this. You will need to add your program executable name
and its path in windows registry.

Let's assume that our application executable is 'test.exe'
and its path is 'c:\testapp'.

1- If you want to run your program every time win98 starts
(after login) you will need to add a String Value in the
following key in registry :

HKEY_LOCAL_MACHINE
\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

Name: test
Type: String (REG_SZ)
Value: c:\testapp\test.exe

If you want your application to run for a specific user you
must change root key to HKEY_CURRENT_USER. In this way your
application will run for the person who was in windows when
creating this key. (usually the person who installs your
software)

2- If you want to run your program every time win98 starts
(before login) you will need to add a String Value in the
following key in registry :

HKEY_LOCAL_MACHINE
\SOFTWARE\Microsoft\Windows\CurrentVersion\RunServices

Name: test
Type: String (REG_SZ)
Value: c:\testapp\test.exe

3- If you want to run a program only once when win98 starts
you will need to add a String Value in the following key in
registry :

HKEY_LOCAL_MACHINE
\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce

Name: test
Type: String (REG_SZ)
Value: c:\testapp\test.exe

After running the application for the first time windows
will clear this application from RunOnce list.

To add this values to specified key you can use install
maker programs such as "Install Shield" or you can write
your own install program that adds these values to registry
when installing your application.

In next issues of this ezine we will see how to install your
application as a Windows NT and 2000 service program that
starts and stops as other service programs. We will also
have articles about registry programming in VB, Delphi and
C++ Builder.

If you have any problem or question about this article you
can ask it in our programming forums and I and other
subscribers will answer your questions. Just visit our
website and leave your message !


Delphi and C++ Builder for "Linux"
Date: | Dec 01 2000
Subject: | Online Programmer Ezine, Volume 1, No.3
Article: | Delphi and C++ Builder for "Linux" !

On September of 1999 Borland announced a new development
environment for Linux platform . 'Kylix' will support C,
C++ and Delphi codes.

Kylix is a component based development environment that is
suitable for GUI, database, Internet and client/server
applications.

It will use CLX Objects. These objects will be compatible
with VCL objects used in Delphi and C++ Builder in windows.

Applications developed by Kylix will run on KDE, GNOME and
any other Linux desktop.

Linux is a fast growing new market. Many programmers are
considering this new market. Kylix is the best choice
for rapid development in this environment.

At the time being Kylix is not available for public but you
can plan porting your Delphi and C++ Builder applications to
Linux environment using Kylix.

To be sure that you will be able to port your applications
you must consider some points :

1- Kylix uses VCL compatible objects . If you use VCL
objects your code will be ported to Kylix easier. Also Avoid
using windows API direct calls.

2- Do not use windows specific objects and features such as
COM objects, ActiveX, OLE and etc.

3- Linux uses Apache web server. Apache supports CGI and
Fast-CGI and Apache API. Kylix will have a lot of facilities
for your Internet applications on Apache.

4- Do not use TASM assembly code. Linux has its own GNU
assembler called 'as'.

Taking above points in mind will make moving to Linux
environment easier.

If you need more information about Kylix you can go to
Borland website.

http://www.borland.com

They have a special website for Kylix now.


Small TCP/IP Hello server with VB 6.0
Date: | Dec 01 2000
Subject: | Online Programmer Ezine, Volume 1, No.3
Article: | Small TCP/IP Hello server with VB 6.0

This article is first part of a two part article for people
who want to start writing socket programming with VB.

This example uses an ocx component that comes with VB. You
will need a from with a command button (command1), a socket
component (winsock1) and a listbox (list1).

We will need to do the following steps to have our hello
server running.

1- We must bind TCP/IP socket to port 1024 when form loads.

2- When we press Listen Key (command1) socket starts
listening port 1024. In this way program will be able to
accept connections. Listening socket is usually used for
just receiving TCP/IP connections. It will also queue
them until our program is free to serve them. We will
usually need another socket to service connections that
has been queued. However as we want to create a small
server we will use a single socket for both listening
and communication with client programs.

3- When a socket on a remote program opens a connection to
our program, a Connection request event is triggered and
ConnectionRequest subroutine is automatically called.
In this subroutine we can accept the connection.

4- Now that everything is prepared, whenever an accepted
socket tries to send us data another event called
DataArrival will be triggered. When we receive this event
we first read data that is sent to us and show it in a
listbox and then send a 'hello' string back to the client
program connected to us. This is why we call this server
a 'hello' server.

5- After sending data, server has no reason to keep
connection so it must close the connection.
When sending data is finished, a SendComplete event is
triggered. As we want to accept more connections we close
socket and then call listen function again to be ready
for accepting other incoming connections.

6- If any error occurs on socket an 'onerror' event is
triggered. In this case we will display an error message.

And now program source:

Private Sub Command1_Click()
Winsock1.Listen
End Sub

Private Sub Form_Load()
Winsock1.Bind 1024
End Sub

Private Sub Winsock1_ConnectionRequest(ByVal requestID As Long)
If Winsock1.State <> sckClosed Then Winsock1.Close
'Load Winsock1(newInstanceIndex)
Winsock1.Accept requestID
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Winsock1.GetData a$, vbString
'received data is in a$ , you can use it
List1.AddItem ("Received : " + a$)
Winsock1.SendData "hello" + vbCrLf
'The string 'hello' is sent in answer to client request
List1.AddItem ("Sent : Hello")
End Sub

Private Sub Winsock1_Error(ByVal Number As Integer,
Description As String, ByVal Scode As Long,
ByVal Source As String, ByVal HelpFile As String,
ByVal HelpContext As Long,
CancelDisplay As Boolean)

MsgBox "Error in Socket" + Description, vbOKOnly, "Error"
End Sub

Private Sub Winsock1_SendComplete()
Winsock1.Close
Winsock1.Listen
End Sub

7- Server written in this article can serve one connection
at a time. If you want you can use more connections by
loading new sockets for each incoming connection.

In next part of this article we will write a client side
program for this server.

Client program will connect server program over network and
will receive 'hello' string and then connection will be
closed by server program. You can test this program by
connecting to port 1024 using a telnet program. Whatever you
send to it, server will answer with a 'hello'.

If you need codes for this article you can visit our site
and go to ezine page. There you will find a link to zipped
source files.


Run Windows Application as a Windows NT Service Program
Date: | January 01, 2001
Subject: | Online Programmer Ezine, Volume 2, No.1
Article: | Run Windows Application as a Windows NT Service Program

In previous part of this article we saw how we can run an
application in background in win98/98. In this article we
will see how we can run our ordinary applications as a
service program. Service programs run in background and start
like any other service in windows NT/2000. You can change
startup type in service start and stop palette.

Again you must be familiar with windows registry before you
can use this article. You will need to add your program
executables names and their path and a few other values in
windows registry.

Let's assume that our application executable is 'test.exe'
and its path is 'c:\testapp'.

1- You will need a file from NT resource kit. Microsoft has
included this file for this purpose but we chose easiest
method to do this. First of all you must copy 'srvany.exe'
file from NT resource kit to application directory.

2- You must add a key in below address with the name you
have chosen for your service.

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services

If we assume TestSrvc will be our service name we must add
below key:

HKEY_LOCAL_MACHINE
\SYSTEM\CurrentControlSet\Services\TestSrvc

3- Then we must add below values in above key

Name: DisplayName
Type: String (REG_SZ)
Value: TestSrvc

Name: ErrorControl
Type: Number (REG_DWORD)
Value: 0x1 (1)

Name: ImagePath
Type: String (REG_SZ)
Value: c:\testapp

Name: ObjectName
Type: String (REG_SZ)
Value: LocalSystem

Name: Start
Type: Number (REG_DWORD)
Value: 0x2 (2)

Name: Type
Type: Number (REG_DWORD)
Value: 0x110 (272)

4- Then we must make a key inside this key with the name
'Parameters' :

HKEY_LOCAL_MACHINE
\SYSTEM\CurrentControlSet\Services\TestSrvc\Parameters

5- Inside this key we must store desired application's path
and exe file name.

Name: Application
Type: String (REG_SZ)
Value: c:\testapp\test.exe

Next time windows NT starts up your application will run
even before you login to console , right after windows
startup. If you want to disable service or change service
type to manual startup you can do this in service start and
startup palette.

To add these values to specified key you can use install
maker programs such as "Install Shield" or you can write
your own install program that adds these values to registry
when installing your application.

In next issues of this ezine we will see how we can add keys
and values to windows registry within our program code in
VB, Delphi and C++ Builder.

If you have any problem or question about this article you
can ask it in our programming forums and I and other
subscribers will answer your questions. Just visit our
website and leave your message in our forums !

http://www.onlineprogrammer.org/forums.html


Small TCP/IP Hello Client Software with VB 6.0
Date: | January 01, 2001
Subject: | Online Programmer Ezine, Volume 2, No.1
Article: | Small TCP/IP Hello Client Software with VB 6.0

This article is second part of a two-part article for
programmers who want to start writing socket programs with
VB.

In previous part of this article we saw how we can write a
simple hello server in VB. We used a socket object that
comes with VB for this purpose. Mswnsock.ocx is a very
stable socket object that we used in our program.

This example uses Winsock component again. You will need a
form with a command button (command1), a socket component
(winsock1) and a list box (list1) in this example.

We will need to do the following steps to have our hello
client connect to our server and communicate with it.

1- This time we don’t need to bind anything.

2- when we press connect key (command1) socket starts
connecting to a server via TCP/IP network. Connect function
needs two parameters before it can connect to a server.

IP address specifies the host that server is running on it.
As we want the client to connect server program running on
our own server we use loop back address that points to our
computer. Loop back address is ‘127.0.0.1’. You can use
address of any other host instead of this.

Second parameter is TCP port. As you know can assign a port
number between 1 and above 65000 to each clinet/server
application.

This is TCP channel we use to avoid communication conflicts
between different programs that communicate between two
hosts. We chose an optional port number of 1024.

3- When a client socket opens a connection to server program,
a connect event is triggered on client program. When we
receive this event we start sending data to server and
also simultaneously show it in listbox1. Message sent to
server is ‘hi!’

4- After server has finished receiving sent data, it sends
back answer data that is ‘hello’ string. It will close
connection after it has sent its data. So closing
connections is done by server side.

5- If any error occurs on socket an 'onerror' event is
triggered. In this case we will display an error message.

And now program source:

Private Sub Command1_Click()
If Winsock1.State <> sckClosed Then
Winsock1.Close
End If
Winsock1.Connect "127.0.0.1", 1024
End Sub

Private Sub Winsock1_Connect()
Winsock1.SendData "Hi!" + vbCrLf
List1.AddItem "Sent to Server: Hi!"
End Sub

Private Sub Winsock1_DataArrival(ByVal bytesTotal As Long)
Winsock1.GetData a$, vbString
List1.AddItem "Received from server: " + a$
End Sub

Private Sub Winsock1_Error(ByVal Number As Integer,
Description As String, ByVal Scode As Long,
ByVal Source As String, ByVal HelpFile As String,
ByVal HelpContext As Long, CancelDisplay As Boolean)

MsgBox "Error in socket : " + Description, vbOKOnly

End Sub

If you need codes for this article you can visit our site
and go to ezine page. There you will find a link to zip
source files.

http://www.onlineprogrammer.org/ezines.html


Shutting down a Windows NT/2000
Date: | February 01, 2001
Subject: | Online Programmer Ezine, Volume 2, No.2
Article: | Shutting down a Windows NT/2000

Shutting down windows 98 is an easy task. You can use a
one-line code:

ExitWindowsEx(EWX_SHUTDOWN,0xffff);

But if you try it on a Windows NT or 2000 you will see that
shut down is not successful. This is because your program
does not have the permission to shut down your server.

This article will show you how to get the permission needed
to shut down the server.

We describe program step by step.

1- We need to know if this is a Windows NT or 2000. If this
is a win98 we will ignore steps needed to get the permission
for shut down because windows 98 does not need so.
IsWindowsNT() function is written for this purpose.

2- We need another function that adjusts permissions so that
our program can shut down server. We have called this
function AdjToken().

3- After we adjusted permissions we can call ExitWindowEx()
function to shut down server.

4- Above steps is implemented inside ShutIt function so this
function will shutdown server regardless of windows type.

You can download source codes from our site.

http://www.onlineprogrammer.org

And now the source code:

int ShutIt()
{
if (IsWindowsNT())
{
AdjToken();
if (GetLastError()!=0)
Application->
MessageBox("Post Adjust Token error","Error",MB_OK);
}

ExitWindowsEx(EWX_SHUTDOWN,0xffff);
return 0;
}

BOOL IsWindowsNT()
{
DWORD dwVersion = GetVersion();

if ( dwVersion < 0x80000000)
return TRUE;
else
return FALSE;
}

void AdjToken()
{
HANDLE hToken;
LUID tmpLuid;

HANDLE handleProcess=GetCurrentProcess();

if(!OpenProcessToken(handleProcess,TOKEN_ADJUST_PRIVILEGES
|TOKEN_QUERY,&hToken))
Application->
MessageBox("Open Process Token Error","Error",MB_OK);

if(!LookupPrivilegeValue(0,"SeShutdownPrivilege", &tmpLuid))
Application->
MessageBox("Lookup PrivilegeValue error","Error",MB_OK);

TOKEN_PRIVILEGES NewState;
LUID_AND_ATTRIBUTES luidattr;

NewState.PrivilegeCount = 1;
luidattr.Luid=tmpLuid;
luidattr.Attributes=SE_PRIVILEGE_ENABLED;
NewState.Privileges[0]=luidattr;

AdjustTokenPrivileges(hToken,
false,
&NewState,
sizeof(TOKEN_PRIVILEGES),
0,
0);

if (GetLastError()!=0)
Application->
MessageBox("Adjust Token Privilage Error","Error",MB_OK);
}


TCP/IP Client/Server software on Unix and Linux
Date: | February 01, 2001
Subject: | Online Programmer Ezine, Volume 2, No.2
Article: | TCP/IP Client/Server software on Unix and Linux (Hello Client)

In previous issues of OnlineProgrammer ezine we saw
client/server programs for windows operating system. We
used a socket Active-X object for those programs.

In Unix operating system we will use BSD sockets library
for network programming. BSD socket functions are the base
for socket functions in other environments too. Winsock
itself is written on this library. There is a port of this
library in other operating systems too.

We start by writing a hello client software. This time we
start with client software, as it is easier to understand.
To test this software you either need the server software
that will be discussed in our next issue or another server
software. You can even use a server software on a windows
platform over TCP/IP network. You will then need remote
computer address to establish TCP/IP connections to it.

We will not have enough time to describe every structure
and function completely but you must be able to write
other programs if you work on this code.

Program is commented on each line so it must be very easy
to understand how it works.

1- First off all we must enter host name in a structure
hostent. This includes the address we want to connect it.

2- After this we must adjust some of connection specifications
in an Internet socket type structure (sockaddr_in). Then we
will use this adjusted structure in our socket functions to
establish the connection. These include socket family
(AF_INET), TCP/IP port (PORT) and remote host address
(s_addr).

3- Now after setting addresses in socket address structures
we can start creating socket. We create our socket by
calling socket(...) function. SOCK_STREAM parameter specifies
that we need a TCP socket.

4- After creation of socket we use connect function to start
connecting to remote host.We use handle to created socket
(sock_descriptor) and internet address structure (sockaddr_in)
as parameters to connect function.

5- Connect function in this example is used in blocking mode.
This means that above function will block program execution
until either a connection is established or a time out or
error is issued. So if we go normally to next instruction
it means that we have connected to remote host and we can
start sending our message.

6- Send function uses a handle to our active socket, buffer
that contains data that we will send and buffer length.
After using buffer for send step we clear buffer to prepare
it for receiving data.

7- After send step we will wait to receive the answer from
server side software on remote computer. (Our own computer
in this example or you can change remote computer address.)

8- Receive function will need a handle to active socket, a
pointer to data buffer and data buffer size as its parameters.

9- After completion of data receive we can close the connection.

And now the source code. You can download source codes from
our site at:

http://www.onlineprogrammer.org

#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>

#define PORT 12000
main(void)
{
char buf[80];
struct sockaddr_in pin;
int sock_descriptor;
int address_size;
struct hostent *server_host_name;
long len;

strcpy(buf,"Hi there"); //message that will be sent

//remote host is local host
server_host_name=gethostbyname("127.0.0.1");
bzero(&pin,sizeof(pin));
pin.sin_family=AF_INET;
pin.sin_addr.s_addr=((struct in_addr *)
(server_host_name->h_addr))->s_addr;

pin.sin_port=htons(PORT); //we are using port 12000

//create socket
sock_descriptor=socket(AF_INET,SOCK_STREAM,0);
connect(sock_descriptor,(void *)&pin,sizeof(pin));
send(sock_descriptor,buf,strlen(buf),0);
bzero(buf,20);
recv(sock_descriptor,buf,80,0);
printf("\nReceived from server : %s\n",buf);
close(sock_descriptor);

}

You can run above code on every Unix or Linux operating
system with minor changes. You will need to include socket
library in compile process. So below line will do it.

$gcc client.c -lsocket -o client

In next issue of this ezine we will see the source code for
server side software.


Shutting down a Windows NT/2000
Date: | March 01, 2001
Subject: | Online Programmer Ezine, Volume 2, No.3
Article: | Start with Perl CGI now! Part I - What's CGI and Hello world!

In issue 1-2 of ezine we had an article about cgi programming.
In that article we saw a small cgi program using C programming
language.

In this issue we will start a series of small articles on cgi
programming in Perl. For those new to cgi programming we start
again from zero. These articles are based on small examples
so you can test them, change them and learn more than the
small example.

When you call a cgi program over internet by referring to its
address in your browser (either directly or indirectly by a
html page) a web server program receives your request. If you
have requested an html file or an image file etc. it easily
sends back the file.

In other side if you have requested a cgi program, web server
does not send cgi program file but runs it and sends back the
result of running the cgi as a html web page.

So actually a cgi program will create an html web page for
web server and this is what web server sends back to browser.

If running a cgi does not create a valid html or return an
error web server will send an error message to the browser.

In this issue we will write a very simple cgi program with
Perl language. We will first see the program and then will
describe each line.

Example 1 - hello.pl:

#!/usr/bin/perl

print "Content-type: text/html\n\n";

print "<HTML>\n";
print "<HEAD><TITLE>Perl Hello World !</TITLE></HEAD>\n";
print "<CENTER><H1>Hello World!</H1></CENTER>\n";
print "</HTML>";

As we told later, this program will output a valid html file.
Web server will get the result and send it to browser. Below
is the actual html file that browser will receive.

<HTML>
<HEAD><TITLE>Perl Hello World !</TITLE></HEAD>
<CENTER><H1>Hello World!</H1></CENTER>
</HTML>

And now description of program.

1- In first line we see the path to Perl interpreter
executable file on server. This is very important on Unix
type servers. If this path does not point to the correct
place of Perl interpreter then our cgi program will not run.

If you are using a NT server with Active state's Perl
(R) then you will not need the first line. Active State
Perl will be used automatically by web server to run
the program.

2- Second line output will create a header that is needed
by web server to accept output of our program as an html
file. You will add this line to your programs exactly as
this line if your program must create an html file.

Pay attention that two "\n" or new line marks are necessary
for the header.

Print command is for sending a text to standard output. If
you run a Perl program from command line the output of print
command will be sent to your console. If you run it inside
a web server ,web server will use the results.

3- In next 4 lines we actually create our html file, as we
want it on the web server. "\n" marks (new line) will force
program to output results in a new line after it.

So we will see have above html code in our browser.

In more complicated programs such as database programs we
will construct the output page from results of longer
processes.

In next issues we will see more complicated examples.

If you have any question about Perl and cgi programming you
can ask it in our programming forums.

http://www.onlineprogrammer.org/forums.html


Shutting down a Windows NT/2000
Date: | March 01, 2001
Subject: | Online Programmer Ezine, Volume 2, No.3
Article: | TCP/IP Client/Server software on Unix and Linux, Part II, Server Software

In previous issues of OnlineProgrammer ezine we saw client
section of our client/server application. In this section we
will see the server side software.

Again we will use BSD socket functions for socket calls.

1- First of all we create a socket by calling socket function.
Function will return a handle to socket, which we will use it
to work with the socket.

2- No we must adjust some of connection specifications in an
internet socket address type structure (sockaddr_in). Then we
will use this adjusted structure in our socket functions to
start listening socket for connections. These include socket
family (AF_INET), IP address of listening network interfaces,
and TCP listening port. INADDR_ANY means that server socket
will listen to all network interfaces.

3- Now after setting addresses in socket address structures we
can start creating socket. We create our socket by calling
socket(...) function. SOCK_STREAM parameter specifies that we
need a TCP socket.

4- To be able to receive requests from clients we must listen
the specified port. For this purpose we bind created socket
to the port and network interface and then call listen function
to start listening. In listen function we have told that socket
can queue up to 20 connections before it can process them.

5- After this we reach inside the main server loop. Here we
wait until we have a connection request to listening socket.
If socket has a pending connection it will return it to the
socket behind accept function. Accept function is a blocking
function. It will block at the function until it receives a
connection.

6- After accept function created a socket connected to remote
host we can receive data from socket connection. Because of
the way we have designed communication protocol for this
client/server application we first start by receiving
information from the connection. "recv" function will put
received data in our buffer.

7- At the end server must send requested information. Here the
information we want to send is only a constant string "hello".
We put this in a buffer and pass it to "send" function.

8- After sending the information we must close temporary socket.

9- Now we can return to the first command in server loop to
serve another connection.

And now the source code. You can download source codes from
our site at:

http://www.onlineprogrammer.org

#include<stdio.h>
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<netdb.h>

main(void)
{
system("clear");
printf("Client:\n");
tcpserv();
}

tcpserv()
{
char buf[8096];
struct sockaddr_in sin;
struct sockaddr_in pin;
int sock_descriptor;
int temp_sock_descriptor;
int address_size;
long len;

int counter=0;

sock_descriptor=socket(AF_INET,SOCK_STREAM,0);

bzero(&sin,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_addr.s_addr=INADDR_ANY;
sin.sin_port=htons(8000); //we are using port 8000

bind(sock_descriptor,(struct sockaddr *)&sin,sizeof(sin));

listen(sock_descriptor,20); //queue up to 20 connections

while(1)
{
//get a temporary socket to handle client request
temp_sock_descriptor= accept
(sock_descriptor,(struct sockaddr *)&pin,&address_size);
//receive data from client
recv(temp_sock_descriptor,buf,8096,0);

strcpy(buf,"hello");
len=strlen(buf);
printf("\nA request arrived\n");
// here we can process the client request
// return data to the client
send(temp_sock_descriptor,buf,len,0);
//close the temporary socket as we are done with it
close(temp_sock_descriptor);
}
}

You can run above code on every Unix or Linux operating
system with minor changes. You will need to include socket
library in compile process. So below line will do it.

$gcc server.c -lsocket -o client

You can find previous articles about this software on our
site.


Programming Articles from Online Programmer Ezine

Programming Articles from Online Programmer Ezine Home

Programming Techniques:
How to make a new style CHM help file
 Run Windows application in background or as a service
Multi Thread Programming in C++ Builder and Delphi
 Run Windows Application as a Windows NT Service Program
 Shutting down a Windows NT/2000 ( C++ Builder and Delphi )
Reviews:
Choosing between Borland Products
 BeOS, Powerful operating system with rich development tools for free
 Delphi and C++ Builder for "Linux" !

Web Programming:
Cgi and Cgi-bin , What are they ? A sample program
 Start with Perl CGI now! Part I - What's CGI and Hello world!

 Network Programming:
Sending Broadcasts with VB and C++Builder App
Small TCP/IP Hello server with VB 6.0
Small TCP/IP Hello Client Software with VB 6.0
 TCP/IP Client/Server software on Unix and Linux (Hello Client)
 TCP/IP Client/Server software on Unix and Linux, Part II, Server Software

Archive of Ezine Articles