Solved

Winscok TCP Client-Server Application

Posted on 2004-10-06
10
324 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
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
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

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Windows Drag & Drop Location 2 94
indy Tmemory stream non latin charcter issue 2 98
add combobox item based on numbers 9 123
Find and Replace Stream with 0s 8 57
The uses clause is one of those things that just tends to grow and grow. Most of the time this is in the main form, as it's from this form that all others are called. If you have a big application (including many forms), the uses clause in the in…
Introduction The parallel port is a very commonly known port, it was widely used to connect a printer to the PC, if you look at the back of your computer, for those who don't have newer computers, there will be a port with 25 pins and a small print…
Migrating to Microsoft Office 365 is becoming increasingly popular for organizations both large and small. If you have made the leap to Microsoft’s cloud platform, you know that you will need to create a corporate email signature for your Office 365…
Internet Business Fax to Email Made Easy - With  eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, f…

920 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

12 Experts available now in Live!

Get 1:1 Help Now