Serversocket example made with API

zhaozj2021-02-17  47

Program Server;

{$ Apptype console}

Uses sysutils, winsock, windows;

TYPE TPARAM = Record Trdid: integer; SCKT: TSOCKET; END;

// Subline function Function ChildThrd (p: pointer): longint; stdcall; var pklen: integer; threadid: integer; asocket: tisocket; buf: array [0..63] of char; begin result: = 0; threadID: = TParam (p ^). Trdid; asocket: = tParam (p ^). Sckt; Writeln ('Thread' INTOSTR (ThreadID) 'Create'); pklen: = 1; While Pklen> 0 Do Begin Fillchar (BUF , SizeOf (BUF), 0); PKlen: = Recv (Asocket, Buf, Sizeof (BUF), 0); // Received Data Write (BUF); if Pklen> 0 The Begin Send (Asocket, BUF, PKLEN, 0 ); // Send data end; end; closesocket (asocket); // Close Socket Dispose (P); Writeln ('Socket' INTOSTR (ASocket) 'Disconnect');

// main var MyWSA: WSAData; Svr, Clt: TSockAddr; NameLen: Integer; hSocket, s: TSocket; TimeOut: integer; ThreadCount: integer; hThread: Thandle; ThreadID: DWord; Param: ^ TParam; begin If WSAStartup ( MakeWord (2, 2), My WSA <> 0 THEN / / Initialization Begin Wsacleanup; Writeln ('wsastartup () fail'; exit; end; hsocket: = socket (AF_INET, SOCK_STREAM, IPPROTO_TCP); // Create Socket IF HSocket = invalid_socket dam ('socket () fail'); exit; end; svr.sin_family: = af_INET; SVR.SIN_PORT: = HTONS (176); // Server port number is 176 SVR.SIN_ADDR.S_ADDR : = inet_addr (PCHAR ('127.0.0.1')); // Server IP address is 127.0.0.1 if Bind (HSocket, SVR, SIZEOF (SVR)) = Socket_ERROR THEN / / Bind Socket Begin CloseSocket (HSocket); WSACLEANUP; WRITELN ('bind () fail'); exit; end; if listen (hsocket, 256) = Socket_ERROR THEN / / Socket Start listening, the maximum number of connections is 256 begin closocket (hsocket); wsacleanup; Writeln 'Listen () fail'); exit; end; timeout: = 3000; threadcount: = 0; Writeln ('listening ... ... '); while true do begin name: = sizeof (CLT); s: = accept (hsocket, @ CLT, @ namelen); // Accept a connection IF s = socket_ERROR THEN BEGIN CloseSocket; wsacleanup; Writeln ('accept () fail'; EXIT; END ELSE BEGIN WRITELN ('socket'); if setsockopt (s, sol_socket, so_rcvtimeo, pchar (@timeout), Sizeof (Timeout) ) = SOCKET_ERROR THEN / / Settings Receive timeout is 3 seconds begin CloseSocket (s); CloseSocket (HSocket); WSACLEANUP; WRITELN ('setsockopt () fail'; exit;

if SetSockOpt (s, SOL_SOCKET, SO_SNDTIMEO, PChar (@TimeOut), SizeOf (TimeOut)) = SOCKET_ERROR then // send timeout set to 3 seconds begin CloseSocket (s); CloseSocket (hSocket); WSACleanup; Writeln ( 'SetSockOpt () Fail '); exit; end; new (param); param ^ .trdid: = threadcount; param ^ .sckt: = s; hthread: = CreateThread (nil, 0, @ ChildThrd, param, 0, threadid); // Create a ChildthRD sub-thread if hthread = 0 Then Begin Writeln ('CreateThread () Fail'; ELSE BEGIN INC (threadCount); end; end; end; clossoSocket (hsocket); // Close Socket wsacleanup; end ./ source code Download http://ono.3322.org/mysoft/serversocket.zip

转载请注明原文地址:https://www.9cbs.com/read-30261.html

New Post(0)