The first is two programs, namely the socket client and server. (Compiled in Windows system vc6.0)
Server-side:
#include <Winsock2.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
void Main ()
{
Wsadata WSD;
SOCKET server; Server socket
Sockaddr_in addrsrv;
Char sendbuf[100];
Char recvbuf[100];
Sockaddr_in addrclient;
SOCKET client; Connected Client socket
int Len;
if (WSAStartup (Makeword (2,2), &WSD)!=0)
{
printf ("Start up failed!\n");
return;
}
Server=socket (af_inet,sock_stream,0); Create Socket
Addrsrv.sin_addr. S_un. S_addr=htonl (Inaddr_any); Set address
Addrsrv.sin_family=af_inet;
Addrsrv.sin_port=htons (6000); Set the port number
bind (server, (sockaddr*) &addrsrv,sizeof (sockaddr)); Binding
Listen (server,5); Set the maximum number of connections
Len=sizeof (SOCKADDR);
while (1)
{
client=accept (server, (sockaddr*) &addrclient,&len); Receiving client Connections
sprintf (SendBuf, "Welcome%s",
Inet_ntoa (ADDRCLIENT.SIN_ADDR));
Send (Client,sendbuf,strlen (SENDBUF) +1,0); Send Information Client
recv (client,recvbuf,100,0); Receiving client Data
printf ("%s\n", recvbuf);
Closesocket (client);
}
Closesocket (client); Close connection
WSACleanup ();
}
Client:
#include <winsock2.h>
#include <stdio.h>
#pragma comment (lib, "Ws2_32.lib")
void Main ()
{
Wsadata WSD;
SOCKET sockclient; Client socket
Sockaddr_in addrsrv;
Char recvbuf[100];
if (WSAStartup (Makeword (2,2), &WSD)!=0)
{
printf ("Start up failed!\n");
return;
}
Sockclient=socket (af_inet,sock_stream,0); Create Socket
Addrsrv.sin_addr. S_un. S_ADDR=INET_ADDR ("127.0.0.1");
Addrsrv.sin_family=af_inet;
Addrsrv.sin_port=htons (6000);
Connect (sockclient, (sockaddr*) &addrsrv,sizeof (sockaddr)); Connect to server Side
recv (sockclient,recvbuf,100,0); Receiving server-side data
printf ("%s\n", recvbuf);
Send (sockclient, "Hello World", strlen ("Hello World") +1,0); Send data to server side
Closesocket (sockclient); Close connection
WSACleanup ();
}
The above two programs only need a simple rewrite, you can implement a simple transfer of files.
Change the information sent by the client to the file name of the sending request.
Send (Sockclient,filename,strlen (filename) +1,0);
The server side received the file name:
Recv (client,filename,100,0);
Server-Side Send file information:
if (Fp=fopen (filename, "RB")) ==null) closesocket (client); The requested file does not exist, the connection is closed
N=fread (SENDBUF,1,100,FP);
while (n>0) {
Send (client,sendbuf,n,0); Send file Client
N=fread (SENDBUF,1,100,FP);
}
The client receives the file information:
if ((Fp=fopen (filename, "WB")) ==null)
{
return;
}
while ((Ret=recv (sockclient,recvbuf,100,0)) >0)
{
Fwrite (RECVBUF,1,RET,FP);
}
Client and server side of socket (Windows console program)