Windows Simple Network socket Programming __ Programming

Source: Internet
Author: User

1. File transfer

File transfer by establishing a server client connection. The client enters a filename, the server searches the element, and after the search succeeds, transmits the data to the client. The client accepts the creation of a file in the current directory.

Hdksjfkl.cpp:Defines the entry point for the console application. #include "stdafx.h" #include <stdio.h> #include <stdlib.h> #include <winsock2.h> #include "iostream
"#define MAXSTRINGSIZE 9000 using namespace std;  
    #pragma comment (lib, "Ws2_32.lib")//Get native IP in_addr gethostname (void) {char host_name[255]; Gets the local host name if (GetHostName (host_name, sizeof (host_name)) = = Socket_error) {cout<< "ERROR%d when get" Ting the local host name.  
        <<wsagetlasterror ();  
        Sleep (3000);  
    Exit (-1);  
    ///From the host name database to get the corresponding "IP" struct hostent *phe = gethostbyname (HOST_NAME); if (phe = = 0) {cout<< "yow!  
        Bad host lookup. ";  
        Sleep (3000);  
    Exit (-1);  
    } struct IN_ADDR addr;  
    memcpy (&AMP;ADDR, phe->h_addr_list[0], sizeof (struct in_addr));   
return addr;  
    //Start server socket StartServer (void) {//create socket socket ServerSocket; if ((Serversocket=socket (AF_INET,SOCK_STREAM,IPPROTO_TCP)) ==invalid_socket) {cout<< "failed to create socket.  
        ";  
        Sleep (3000);  
    Exit (-1);  
    Short port=1986;  
    struct sockaddr_in serveraddress;  
    Initializes the specified memory area memset (&serveraddress,0,sizeof (sockaddr_in));  
    Serveraddress.sin_family=af_inet; Serveraddress.sin_addr. S_un.  
    S_ADDR = htonl (Inaddr_any);  
	
    Serveraddress.sin_port = htons (port); Bind if (Bind (ServerSocket, (sockaddr*) &serveraddress,sizeof (serveraddress)) ==socket_error) {Cout<&lt ;" Socket binding to port failed.  
        Port: "<<port;  
        Sleep (3000);  
    Exit (-1); //Enter listening status if (Listen (serversocket,somaxconn) ==socket_error) {cout<<) listening failed.  
        ";  
        Sleep (3000);  
    Exit (-1);   
    //Get server IP struct in_addr addr = GetHostName ();  
    cout<< "Server" <<inet_ntoa (addr) << ": <<port<<" is listening ... "<<endl; Return ServerSocket;
	//Receive Client connection Socket Receiveconnect (socket &serversocket) {char sendbuffer[80] = {0};
    int bytes; Socket clientsocket;//Socket struct sockaddr_in that is used to communicate with the client clientaddress;//socket address memset (&clientaddress  
	
    , 0,sizeof (clientaddress))//initializes the memory int addrlen = sizeof (clientaddress) that holds the client information;  
        Accept connection if ((Clientsocket=accept (ServerSocket, (sockaddr*) &clientaddress,&addrlen) ==invalid_socket) { cout<< "Accept client connection failed.  
        ";  
        Sleep (3000);  
    Exit (-1);
	} cout<< "Accept connection from" <<inet_ntoa (CLIENTADDRESS.SIN_ADDR) <<endl;  sprintf (Sendbuffer, "welcome\r\n");
    Send welcome message to Client bytes = Send (Clientsocket,sendbuffer,strlen (Sendbuffer), 0);  
return clientsocket;
		} void Sendfile (SOCKET &serversocket) {while (1) {//Accept client command and invoke handler function FILE * fp = NULL;
		Char buf[30];
		Char senmm[10];
		memset (senmm,0,sizeof (SENMM));
		Char sendbuf[500]; memset (sendbuf,1,sizeof) (sendBUF));
		Char maxbuf[500];	
		memset (maxbuf,1,sizeof (MAXBUF));
		Char sendmsg[50];
		memset (sendmsg,0,sizeof (sendmsg));
		SOCKET Clientsocket = Receiveconnect (ServerSocket);
		do {memset (buf,1,sizeof (BUF));
		int bytes = 0;
			if ((bytes = recv (Clientsocket,buf,strlen (BUF) +1,0)) ==socket_error) {sprintf (sendmsg, "Receive data failed");
			Send (Clientsocket,sendmsg,strlen (sendmsg), 0);
		Break
		} if (fp = fopen (buf, "r") = = NULL) {sprintf (senmm, "filename error");
		Send (Clientsocket,senmm,strlen (SENMM) +1,0);
		printf ("The file name from the client is not \ n");
		printf ("%d bytes \ n", bytes);
			else {sprintf (senmm, "250");	
			Send (CLIENTSOCKET,SENMM, strlen (senmm) + 1,0);
			printf ("Client sends file download request, filename is%s\n", buf);
			Break
		Sleep (3000);
		}}while (1);
		Sleep (3000);
		Char mmmm[1000];
		Mmmm[0] = ' the ';
		while (Fgets (MAXBUF,80,FP)!= NULL) {//loop reads the file and sends it through H_newsocket to client printf ("%s\n", maxbuf);
			sprintf (SendBuf, "%s", maxbuf);
			strcat (MMMM,MAXBUF); Send (Clientsocket,maxbuf,strlen (MAXBUF) + 1,0);
		printf (".");
		*/printf ("%s", sendbuf);
		Fclose (FP);
		printf ("%s", MMMM);
		Send (Clientsocket,mmmm,strlen (MMMM) + 1,0);
		sprintf (SENMM, "266");
		Send (Clientsocket,senmm,strlen (SENMM) + 1,0);
	Closesocket (Clientsocket);
	int main (int argc, char* argv[]) {wsadata wsa; if (WSAStartup (Makeword (2,2), &AMP;WSA)!= 0) {printf (socket initialization failed!!)
		\ n ");
		Sleep (3000);
	Exit (-1);
	SOCKET ServerSocket = StartServer ();
	
	Sendfile (ServerSocket);
return 0;
 }
The above is the code for the server segment.

Hdksjfklclien.cpp:Defines the entry point for the console application. #include "stdafx.h" #include <windows.h> #include <process.h> #include <iostream> #include "  
String.h "using namespace std;   
    #pragma comment (lib, "Ws2_32.lib")//Receive data void receive (socket socket) {char buf[2096];  
    int bytes;  
            if ((Bytes=recv (socket,buf,sizeof (BUF), 0)) ==socket_error) {printf ("Failed to receive data!\n");  
        Exit (-1);  
        } buf[bytes]= ';   
cout<<buf<<endl;  
    //Get server IP unsigned long getserverip (void) {//Convert the IP address of the string to U_long char ipstr[20];  
	Fills the memory referred to in the first argument with the second parameter, the size of the third parameter memset (ipstr,0,sizeof (IPSTR));  
	cout<< "Please enter the server IP you want to link:";  
	cin>>ipstr;
    strcpy (Ipstr, "127.0.0.1");  
    unsigned long IP;  
        if ((Ip=inet_addr (IPSTR)) ==inaddr_none) {cout<< "Illegal IP address:";  
        Sleep (3000);  
    Exit (-1);  
} return IP; }  
Send data char path[80] = {' 0 '};
	void Sendmsg (SOCKET &sock) {printf ("Please enter the filename to download \ n");
	scanf ("%s", path);
        printf ("%d\n", strlen (path)); if (Send (Sock,path,strlen (path) +1,0) ==socket_error) {cout<< failed to send data.  
            ";  
        Exit (-1);
cout<< "Send data is" <<path<<endl;  
    }//link server void CConnect (SOCKET &sock) {unsigned long ip=getserverip ();  
    Converts the port number to an integer short port=1986;  
    cout<< "Connecting to" <<inet_ntoa (* (in_addr*) &ip) << ":" <<port<<endl;  
    struct sockaddr_in serveraddress;  
    memset (&serveraddress,0,sizeof (sockaddr_in));  
    Serveraddress.sin_family=af_inet; Serveraddress.sin_addr. S_un.  
    s_addr= IP;  
    Serveraddress.sin_port = htons (port); Establish a connection to the server if (Connect (sock, (sockaddr*) &serveraddress,sizeof (serveraddress)) ==socket_error) {cout<& lt; "   
        Failed to establish connection: "<<wsagetlasterror ();  
        Sleep (3000);Exit (-1);  
    int main (int argc, char* argv[]) {wsadata wsa;  
        Initialize socket DLL if (WSAStartup (Makeword (2,2), &AMP;WSA)!=0) {cout<< "socket initialization failed!";  
        Sleep (3000);  
    Exit (-1);  
    ///create socket socket sock; The If ((Sock=socket (AF_INET,SOCK_STREAM,IPPROTO_TCP)) ==invalid_socket) {cout<< failed to create a socket.  
        ";  
    Exit (-1);
	} cconnect (sock);//Linked server Receive (sock);	
	
	Char buf[10];	
		while (1) {if (strncmp (buf, ",", Strlen ("(") + 1) = 0)) break;
		Sendmsg (sock);
			
	Recv (Sock,buf,strlen (BUF) + 1,0);
	} FILE *FP;
	Char recvbuf[1000];
	memset (recvbuf,1,sizeof (RECVBUF));
		if (fp = fopen (Path, "w+") = = NULL) {printf ("Local open file error \ n");
	return 0;
	}//int bytee = 0;
	 printf ("%s\n", recvbuf);
	 Recv (Sock,recvbuf,sizeof (RECVBUF), 0);
	printf ("%s", recvbuf);

	
	fprintf (FP,RECVBUF);
	Fclose (FP);
	Closesocket (sock);
	WSACleanup ();
	printf ("File received \ n");
return 0;
 }

The above is the client code.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.