Winscok TCP Client-Server Application

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
LVL 2
StTwisterAsked:
Who is Participating?
 
RenegadeBBSConnect With a Mentor Commented:
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
 
HypoviaxCommented:
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
 
HypoviaxCommented:
Sending files is quite difficult with winsock but i have code if you really want :)

Hypoviax
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

 
HypoviaxCommented:
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
 
StTwisterAuthor Commented:
You didn't understand me well. I don't want to use any COMPONENTS, only the WINSOCK UNIT.

Thanks.
0
 
HypoviaxCommented:
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
 
RenegadeBBSCommented:


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
 
StTwisterAuthor Commented:
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
 
RenegadeBBSCommented:
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
 
StTwisterAuthor Commented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.