WINSOCK program design preliminary <3> Source Program Example (2)

zhaozj2021-02-11  195

// a SimpleSt Web Client

// Written by Shen Zhiliang for Learning Winsock & HTTP

//zhiliang@sina.com

//1998.7.29

#include "winsock.h"

#include "stdio.h"

#define buflen 4096

Void socketError (Char * Call)

{

FPRINTF (stderr, "Winsock Error # function:% s, error code:% ld / n", call, wsagetlasterror ());

}

Main (int Argc, char ** argv)

{

INT IRES, IPORT, ITMP;

Socket S, RS;

SockAddr_in sin, rsin;

Wsadata WSAD;

Word WVersionReq;

Char recvbuf [buflen];

IF (Argc <4)

{

FPRINTF (stderr, "usage: sockserver ip port message / n");

Return -1;

}

IF (INET_ADDR (Argv [1]) == inaddr_none)

{

FPRINTF (stderr, "error ip gaving / n");

Return -1;

}

iPort = 0;

Iport = ATOI (Argv [2]);

Sin.sin_addr.s_addr = inet_addr (argv [1]);

Sin.sin_family = pf_inet;

Sin.sin_port = HTONS (iPort);

IF (iPort <= 0)

{

FPRINTF (stderr, "must specify a number for port / n");

Return -1;

}

WversionReq = makeword (1, 1);

Ires = WSAStartup (WVersionReq, & WSAD);

IF (IRES! = 0)

{

"" "WSAStartup ()");

Return -1;

}

S = Socket (PF_INET, SOCK_STREAM, 0);

IF (s == invalid_socket)

{

SocketError ("socket ()");

Return -1;

}

ITMP = SIZEOF (SIN);

FPrintf (stderr, "Winsock Client Start ... / N");

IF (Connect (S, LPSOCKADDR) & Sin, ITMP) == Socket_ERROR)

{

SocketError ("Connect ()");

CloseSocket (s);

WSACLEANUP ();

Return -1;

}

STRCPY (Recvbuf, Argv [3]);

STRCAT (Recvbuf, "/ R / N / R / N");

IRES = Send (S, Recvbuf, Strlen (Recvbuf), 0);

IF (Ires == Socket_ERROR)

{

SocketError ("Send ()");

CloseSocket (s);

WSACLEANUP ();

Return -1;

}

Printf ("SENT DATA: / N ---------------- / N% S / N ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ / N ", Recvbuf);

FILE * fp = fopen ("send.dat", "a b"); if (fp == null)

Return -1;

Ires = RECV (S, Recvbuf, Bufflen, 0);

While (Ires! = Socket_ERROR && IRES! = 0)

{

Printf ("Received Data: / N ------------------ / N% S / N ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ / N ", Recvbuf);

FWRITE (Recvbuf, Sizeof (Char), IRES, FP);

Ires = RECV (S, Recvbuf, Bufflen, 0);

}

Fclose (fp);

CloseSocket (s);

WSACLEANUP ();

Return 0;

}

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

New Post(0)