First use of Dev C + + for the socket programming process in Windows

Source: Internet
Author: User
Tags htons

Remember the first contact socket programming, in devc++ using Winsock for socket programming process, by creating 2 projects in Devc++ is the server, client program project, Feel the client communicating with the server through the socket.

1. New project is different from the usual, not only need to create a C file, but also to add libws2_32 in the connection library to configure the connection library properties in project management, and then create a new server.c in the project connection-oriented c/S program Workflow (TCP)
    1. Use the WSAStartup () function to check the installation of the System protocol stack
    2. Create a server-side communication socket using the socket () function
    3. Bind the created socket to the server address using the bind () function
    4. Prepare the server socket for receive connection requests using the Listen () function
    5. Use Accept () to receive connections from the client from the Connect () function,
    6. After a connection request is established, send data using the Send () function or use the recv () function to receive data
    7. Use the closesocket () function to close the socket (you can first close the read-write channel with the Shutdown () function)
    8. Finally call the WSACleanup () function to end the Winsock Sockets API
Server code:
#pragmaComment (lib, "Ws2_32.lib")#include<Winsock2.h>#include<stdio.h>#include<stdlib.h>#defineDefault_port 5050//Service-Side default portintMainintargcChar*argv[]) {intIport =Default_port; Wsadata Wsadata; SOCKET slisten,saccept;intIlen;//Client Address lengthintIsend;//Send data lengthCharBuf[] ="I am a server";//information to send to the customerstructSockaddr_in ser,cli;//addresses of servers and customersif(WSAStartup (Makeword (2,2), &wsadata)! =0) {printf ("Failed to load winsock.\n");//Winsock Initialization Errorreturn-1;} Slisten= Socket (Af_inet,sock_stream,0);//Create a server-side socketif(Slisten = =invalid_socket) {printf ("socket () Failed:%d\n", WSAGetLastError ());return-1;}//The following initializes the server-side addressser.sin_family = af_inet;//use IP address familySer.sin_port = htons (Iport);//host sequence port number converted to network byte-order port numberSER.SIN_ADDR.S_ADDR = htonl (Inaddr_any);//Host-order IP address translates to network byte-order host address//use the system-specified IP address Inaddr_anyif(Bind (Slisten, (LPSOCKADDR) &ser,sizeof(Ser)) = = Socket_error)//binding to the address of a socket{printf ("bind () Failed:%d\n", WSAGetLastError ());return-1;}if(Listen (Slisten,5) = = Socket_error)//Enter listening status{printf ("Lisiten () Failed:%d\n", WSAGetLastError ());return-1;} Ilen=sizeof(CLI);//initializing client address length parameters while(1)//Enter the loop waiting for the customer's connection request{saccept= Accept (Slisten, (structSOCKADDR *) &cli,&Ilen);if(Saccept = =invalid_socket) {printf ("Accept () Failed:%d\n", WSAGetLastError ());return-1;} printf ("Accepted Client ip:[%s],port:[%d]\n", Inet_ntoa (CLI.SIN_ADDR), Ntohs (Cli.sin_port));//output client IP address and port numberIsend = Send (Saccept,buf,sizeof(BUF),0);//send a message to the clientif(Isend = = socket_error)//Error Handling{printf ("Send () Failed:%d\n", WSAGetLastError ()); Break;}Else if(Isend = =0){ Break;}Else{printf ("send () byte:%d\n", isend);//Output Bytes sent successfully}closesocket (saccept);} Closesocket (Slisten); //Close SocketWSACleanup ();//Output Bytes sent successfullyreturn 0;}
2. Save the final build and run the project and compile the build Server.exe. Server Project Structure:3. Create a new client project in the same way, compile and build client.exe. connection-oriented c/S program Workflow (TCP)
    1. Use the WSAStartup () function to check the installation of the System protocol stack
    2. Create a client socket using the socket () function
    3. Use the Connect () function to make a request to make a connection to the server (without the bind () port number before the call can be completed automatically by the system)
    4. Send data using the Send () function after the connection is established, or receive data using the recv () function
    5. Use the Closesocet () function to close a socket
    6. Finally call the WSACleanup () function to end the Winsock Sockets API
Client code:
#pragmaComment (lib, "Ws2_32.lib")#include<Winsock2.h>#include<stdio.h>#include<stdlib.h>#defineData_buffer 1024//Default buffer sizeintMainintargcChar*argv[]) {Wsadata wsadata; SOCKET sclient;intIport =5050;intIlen;//the length of data received from the server sideCharBuf[data_buffer];//Receive BuffersstructSockaddr_in ser;//server-side addressif(argc<2)//determine if the parameter input is correct: client [Server IP]{printf ("usage:client [Server IP address]\n");//command-line promptreturn-1;} memset (BUF,0,sizeof(BUF));//initializing the Receive bufferif(WSAStartup (Makeword (2,2), &wsadata)! =0) {printf ("Failed to load winsock.\n");//Winsock Initialization Errorreturn-1;} Ser.sin_family= Af_inet;//Initializing server address informationSer.sin_port = htons (Iport);//Port conversion to network byte orderSER.SIN_ADDR.S_ADDR = inet_addr (argv[1]);//IP address converted to network byte orderSclient = socket (Af_inet,sock_stream,0);//Create a client-side streaming socketif(Sclient = =invalid_socket) {printf ("socket () Failed:%d\n", WSAGetLastError ());return-1;}//request to establish a TCP connection to the server sideif(Connect (sclient,structSOCKADDR *) &ser,sizeof(Ser)) ==invalid_socket) {printf"Connect () Failed:%d\n", WSAGetLastError ());return-1;}Else{Ilen= Recv (Sclient,buf,sizeof(BUF),0);//receiving data from the server sideif(Ilen = =0)return-1;Else if(Ilen = =socket_error) {printf ("recv () Failed:%d\n", WSAGetLastError ());return-1;}Elseprintf ("recv () data from server:%s\n", buf);//output Receive data}closesocket (sclient); //Close SocketWSACleanup ();return 0;}
4. Running result: Start Server.exe, and finally start the CLIENT.EX program communication with the server (client each connection, will receive a message from the service side, the service side on each incoming access will print access to IP and port)

Use dev C + + for socket programming during Windows first

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.