Solved

Winscok TCP Client-Server Application

Posted on 2004-10-06
10
320 Views
Last Modified: 2010-04-04
Hi,

I will like to build a client server apllication, using pure Winsock without any other components, or sockets. The reason for this is that i want the application to be as small as possible, so i won't be using any forms. I would also like to use async sockets. It would be excelent if u will also make some procedures for receving, sending text and files.

Thanks.

StTwister
0
Comment
Question by:StTwister
  • 4
  • 3
  • 3
10 Comments
 
LVL 5

Expert Comment

by:Hypoviax
ID: 12245782
This is a little example that allows a user to request a new password remotely (you could easily adjust this to make a chat program etc). I have added comments such as SENDING etc to illustrate the key sections that are involved in using the Winsock control

If you are using Delphi 7 (or 8) you will have to do this first (if you are not ignore this bit):

Go to Project|Options|Packages then 'Add' then in the window that opens, go to where delphi is installed then to \Bin and find 'dclsockets70.bpl' and add that in.

Next go to the Internet tab and add a TServerSocket and TClientSocket control (not the green coloured ones). In the properties of the serversocket add a port number (high up like 8000) and make it active. Rename it "server". In the clientsocket properties set the port number to the same number as the server port number. Rename this control "Client". Add the following events to each control except the very first which will go into your block event procedure

THE EXAMPLE:

<<<

procedure TForm1.Button1Click(Sender: TObject);
begin     //Add this event when the block event occurs
client.Socket.SendText('Requesting Password') //SENDING CLIENT
end;

procedure TForm1.ServerClientRead(Sender: TObject;  //RECIEVING SERVER
  Socket: TCustomWinSocket);
var password, data:string  ;
  begin
data:=socket.recievetext; //RECIEVING SERVER
Showmessage('Request has been made for a new password at ' + socket.RemoteHost);
password:=inputbox('New Password','Enter a new password','');
socket.SendText(password) ; //SENDING SERVER
end;

procedure TForm1.ClientRead(Sender: TObject; Socket: TCustomWinSocket); //RECIEVING CLIENT
begin
messagedlg('You are allowed to continue. Your new password is ' + socket.ReceiveText,mtinformation,[mbok],0);
end;

procedure TForm1.FormCreate(Sender: TObject); //CONNECTING
begin
client.Address:='127.0.0.1';   //This is where the address of the server will be (127.0.0.1 points to the local computer)
client.Active:=true;
end;

>>>

Hope this helps,

Regards,

Hypoviax
0
 
LVL 5

Expert Comment

by:Hypoviax
ID: 12245790
Sending files is quite difficult with winsock but i have code if you really want :)

Hypoviax
0
 
LVL 5

Expert Comment

by:Hypoviax
ID: 12245797
Actually here is the example i used myself for sending files:

http://www.planet-source-code.com/vb/scripts/ShowCode.asp?txtCodeId=783&lngWId=7

Regards,

Hypoviax
0
 
LVL 2

Author Comment

by:StTwister
ID: 12252864
You didn't understand me well. I don't want to use any COMPONENTS, only the WINSOCK UNIT.

Thanks.
0
 
LVL 5

Expert Comment

by:Hypoviax
ID: 12254027
Sorry, it thought you meant only other third party components. You may be able to use this same method but will have to actively create each event (others will expand on this hopefully because it makes it a lot more difficult) e.g:

var server:tserversocket;

server:=tserversocket.create;

You have then to control the events etc .I am not completely sure on how to do this but it may have some thing to do with:

server.OnClientRead etc

If you declare the sockets globally you may be able to add those procedures (you'll have to try it because i'm not completely sure in this regard)

Regards,

Hypoviax
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 1

Expert Comment

by:RenegadeBBS
ID: 12257409


http://www.swissdelphicenter.ch/torry/showcode.php?id=2134

It's a smtp server, but you can use snippets on how to do raw sockets without vcl.
0
 
LVL 2

Author Comment

by:StTwister
ID: 12261333
Hypoviax: I don't want to use any components like TServerSocket, TClientSocket... I only want to use the WinSock unit.

RenegadeBBS: That code is to complex. I only need to send strings and files. Could u simplify it?

Thanks.
0
 
LVL 1

Accepted Solution

by:
RenegadeBBS earned 250 total points
ID: 12265486
I can show you text, but when files comes into play.. I am not that bright on doing Stream stuff.
Now, if you want low level api stuff it is going to be large and complicated.  It's the nature of it, but
the end result will produce a smaller code base.

http://www.nullterminator.net/winsock.html
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/winsock/winsock/winsock_functions.asp
first page of: http://tiger.la.asu.edu/Quick_Ref/Socket_quickref.pdf

Here is something I hacked out.  You really should take the time to read each of the above sites and
learn how to error check this code.  Learn how to make this threaded and how to create more then
one open socket for recv and sending within' the same program.

-=-=-=-=--=-=-
program Project1;

{$APPTYPE CONSOLE}

uses
  SysUtils, WinSock;

procedure SockSetup;
var WSAData  : TWSAData;
begin
    WSAStartup(MakeWord(2, 0), WSAData);
    MainSocket := Winsock.Socket(AF_INET, SOCK_STREAM, 0);
end;

procedure SocketBind;
var SockAddr : TSockAddrIn;
begin
    FillChar(SockAddr, SizeOf(SockAddr), 0);
    SockAddr.Sin_Family := AF_INET;
    SockAddr.Sin_Port := HtoNS(23);
    SockAddr.Sin_Addr.S_Addr := INADDR_ANY;

    Winsock.Bind(MainSocket, SockAddr, SizeOf(SockAddr))
end;

procedure SocketListen;
begin
    Winsock.Listen(MainSocket, 3);
end;

function SocketConnection: boolean;
var FD     : TFDSet;
    TimeVal: TTimeVal;
    SizeSA : Integer;
    SA     : TSockAddr;
begin

    FD_Zero(FD);
    FD_Set(MainSocket, FD);
    TimeVal.TV_Sec := 0;
    TimeVal.TV_USec := 0;
    Winsock.Select(0, @FD, nil, nil, @TimeVal);

    FillChar(SA, SizeOf(SA), 0);
    SizeSA := SizeOf(SA);
   if  Winsock.Accept(MainSocket, @SA, @SizeSA) = SOCKET_ERROR then SocketConnection := false
   else SocketConnection := true;
end;

procedure SocketConnect;
var
    SockAddr.sin_family := AF_INET;
    SockAddr.sin_port   := htons(23);
    SockAddr.sin_addr.S_addr := inet_addr(PChar('192.168.1.101'));

    WinSock.Connect(MainSocket, SockAddr, SizeOf(SockAddr));
end;

procedure SocketRecv;
var FD     : TFDSet;
    TimeVal: TTimeVal;
    Result : Integer;
begin
   
    TV.tv_sec := 0;
    TV.tv_usec := 0;
    FD_Zero(FD);
    FD_Set(MainSocket, FD);
    Result := Select(0, @FD, nil, nil, @TV);
    if (Result <> SOCKET_ERROR) and (Result <> 0) then begin
        FillChar(Buff,SizeOf(Buff),#0);
        WinSock.Recv(MainSocket, Buff, SizeOf(Buff), 0);
    end;
end;

procedure SocketSend;
begin
  WinSock.Send(MainSocket, Buff, SizeOf(Buff), 0);
end;

procedure SocketShutDown;
begin
   WinSock.Shutdown(MainSocket, 2);
end;

procedure SocketClose;
begin
   WinSock.CloseSocket(MainSocket);
   WSACleanUp;
end;

var
  Buff : array[0..32635] of Char;
  MainSocket, NewSocket : TSocket;

begin
//be connectted to.
  SocketSetup
  SocketBind;
  SocketListen;
  repeat until SocketConnection;
  SocketRecv;
  writeln(Buff);
  Buff := 'Thanks';
  SocketSend;
  SocketShutDown;
  SocketClose;
end.

or

begin
//connect to something.
  SocketSetup
  SocketConnect;
  Buff := 'Hello World';
  SocketSend;
  SocketRecv;
  Writeln(Buff);
  SocketShutDown;
  SocketClose;
end.
0
 
LVL 1

Expert Comment

by:RenegadeBBS
ID: 12265501
Quote:
"Sorry, it thought you meant only other third party components. You may be able to use this same method but will have to actively create each event (others will expand on this hopefully because it makes it a lot more difficult)"

Yep, they would have to build the object themself instead of the vcl doing it for them.. but if they want to go to a threaded enviroment then they would have to do this anyhow, but with winsock api functions they could do the same thing but without trigger'd events.  ie  OnConnect.. OnDataRecv etc.. which is sort of not good.

but shrug..
0
 
LVL 2

Author Comment

by:StTwister
ID: 12265528
OK, that was very good, but the code is using non-blocking sockets, isn't it? I want to use asynchronous (did i spell that right???) sockets.

Thanks
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

This article explains how to create forms/units independent of other forms/units object names in a delphi project. Have you ever created a form for user input in a Delphi project and then had the need to have that same form in a other Delphi proj…
In this tutorial I will show you how to use the Windows Speech API in Delphi. I will only cover basic functions such as text to speech and controlling the speed of the speech. SAPI Installation First you need to install the SAPI type library, th…
This demo shows you how to set up the containerized NetScaler CPX with NetScaler Management and Analytics System in a non-routable Mesos/Marathon environment for use with Micro-Services applications.
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…

744 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now