Socket Programming Learning for C + +

Source: Internet
Author: User
Tags htons

Preface

Have to admit that as a front-end development, there is still a background development dream. Start learning from socket communications, add learning points to your work, and document the learning process.

  PS: Can a friend of the park recommend some related books?

Service Side

The server code is as follows, after setting listen, the corresponding socket connection is obtained through accept and the thread is created to communicate, and the corresponding thread is closed after the communication is completed.

//socket_service.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<stdio.h>#include<Winsock2.h>#pragmaComment (lib, "Ws2_32.lib")#defineListen_max_count 5DWORD WINAPI answerthread (LPVOID lparam) {printf ("Thread id:%4d create!\n", GetCurrentThreadID ()); intret; Charbuf[ -] = {0 }; Charsendbuf[ the] = {0 }; SOCKET Clientsocket=(SOCKET) (LPVOID) lparam;  while(true) {memset (buf,0,sizeof(BUF)); RET= Recv (Clientsocket, buf,sizeof(BUF),0); if(ret<=0)        {             Break; } printf ("REVC:%s\n", BUF); sprintf_s (SendBuf,"Thread id:%4d revced", GetCurrentThreadID ()); RET= Send (Clientsocket, SendBuf, strlen (SENDBUF) +sizeof(Char),0); if(Ret <=0)        {             Break; }} printf ("Thread id:%4d stop!\n", GetCurrentThreadID ());    Closesocket (Clientsocket); return 1;}int_tmain (intARGC, _tchar*argv[])    {WORD wversionrequested;    Wsadata Wsadata; Wversionrequested= Makeword (1,1); if(WSAStartup (wversionrequested, &wsadata) = =invalid_socket) {        return 0; }    if(Lobyte (wsadata.wversion)! =1||hibyte (wsadata.wversion)!=1) {wsacleanup (); return 0; } SOCKET socksrv= Socket (Af_inet, Sock_stream,0); intLen =sizeof(SOCKADDR);    Sockaddr_in clientaddr;    Sockaddr_in serviceaddr; Serviceaddr.sin_addr. S_un. S_addr=htonl (Inaddr_any); Serviceaddr.sin_family=af_inet; Serviceaddr.sin_port= Htons (27015); if(Bind (Socksrv, (sockaddr*) &serviceaddr, len) = =invalid_socket) {printf ("failed bind!\n");        Closesocket (SOCKSRV);        WSACleanup (); return 0; }    if(Listen (socksrv, listen_max_count) = =socket_error) {printf ("Listen failed with error:%ld\n", WSAGetLastError ());        Closesocket (SOCKSRV);        WSACleanup (); return 0;    } SOCKET sockclient; HANDLE Hthread=NULL;    DWORD dwThreadID;  while(1) {sockclient= Accept (Socksrv, (sockaddr*) &clientaddr, &Len); Sleep ( +); Hthread= CreateThread (null, NULL, Answerthread, (LPVOID) sockclient,0, &dwThreadID); if(Hthread = =NULL) {printf ("creatthread answerthread () failed.\n");    }} closesocket (SOCKSRV);    WSACleanup (); return 0;}

Client

The client code is as follows, and after the connection succeeds, the loop enters for the communication conversation.

//socket_client.cpp: Defines the entry point of the console application. //#include"stdafx.h"#include<stdio.h>#include<Winsock2.h>#pragmaComment (lib, "Ws2_32.lib")int_tmain (intARGC, _tchar*argv[])    {WORD wversionrequested;    Wsadata Wsadata; interr; Wversionrequested= Makeword (1,1); if(WSAStartup (wversionrequested, &wsadata) = =invalid_socket) {        return-1; }    if(Lobyte (wsadata.wversion)! =1||hibyte (wsadata.wversion)!=1) {wsacleanup (); return-1; } SOCKET sockclient= Socket (Af_inet, Sock_stream,0); intLen =sizeof(SOCKADDR);    Sockaddr_in Local; Local.sin_addr. S_un. S_addr= Inet_addr ("192.168.1.15"); Local.sin_family=af_inet; Local.sin_port= Htons (27015); if(Connect (sockclient, (sockaddr*) &local, len) = =invalid_socket) {printf ("Connect error/n"); return 0; }    Charinputbuf[ -]; Charrecvbuf[ -]; intret;//While (scanf_s ("%s", Inputbuf, sizeof (INPUTBUF))! = EOF)     while(gets_s (inputbuf)) {if(strcmp (Inputbuf,"Stop") ==0)        {             Break; } ret= Send (Sockclient, Inputbuf, strlen (INPUTBUF) +sizeof(Char),0); if(ret<=0) {printf ("Send failed!\n");  Break; } ret= Recv (Sockclient, Recvbuf,sizeof(RECVBUF),0); if(Ret <=0) {printf ("recv failed!\n");  Break; } printf ("My reply is:%s\n", RECVBUF); //printf ("%s\n", Inet_ntoa (LOCAL.SIN_ADDR));} closesocket (sockclient);    WSACleanup (); return 0;}

Test

Hello world!!

1, open more than one client, you can see the server as follows to output the creation of multiple threads.

  

2, the client input Hello world!, can get the server reply, and tell which server thread received the message.

  

3, close one of the clients, you can see the corresponding thread is also closed.

4, close the server, you can enter any content, you can see the client also received a prompt to send failed and shut down.

Socket Programming Learning for C + +

Related Article

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.