A network socket is an internal endpoint for sending or receiving data at a single node in a computer network.
I write a Echo Program Demo that will send what it receives.
#include "stdafx.h"
#include "ws2tcpip.h"
#include "winsock2.h"
#pragma comment (lib,"ws2_32.lib") //load ws2_32.dll
#define BUF_SIZE 100
int_tmain(intargc,_TCHAR*argv[]){//initialize struct WSADATAWSADATAwsaData;WSAStartup(MAKEWORD(2,2),&wsaData);//version:2.2//create server socketSOCKETserverSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//IPv4 address, TCP protocol//bind socketsockaddr_insockAddr;memset(&sockAddr,0,sizeof(sockAddr));sockAddr.sin_family=AF_INET;//IPv4 addressinet_pton(AF_INET,"127.0.0.1",&sockAddr.sin_addr);//LOCALHOST IP addresssockAddr.sin_port=htons(1234);//port numberbind(serverSock,(SOCKADDR*)&sockAddr,sizeof(SOCKADDR));//listenlisten(serverSock,20);//20: length of request queue//receive request from clientSOCKADDRclientAddr;intnSize=sizeof(SOCKADDR);charbuffer[BUF_SIZE]={0};while(1){SOCKETclientSock=accept(serverSock,&clientAddr,&nSize);//accept request from clientintstrLen=recv(clientSock,buffer,BUF_SIZE,0);//receive data from clientprintf("string from client: %s\n",buffer);send(clientSock,buffer,strLen,0);//send data to clientclosesocket(clientSock);//close client socketmemset(buffer,0,BUF_SIZE);}//close server socketclosesocket(serverSock);//terminate use of ws2_32.dllWSACleanup();return0;}
#include "stdafx.h"
#include "ws2tcpip.h"
#include "winsock2.h"
#pragma comment (lib,"ws2_32.lib") //load ws2_32.dll
#define BUF_SIZE 100
int_tmain(intargc,_TCHAR*argv[]){//initialize struct WSADATAWSADATAwsaData;WSAStartup(MAKEWORD(2,2),&wsaData);//version:2.2//send request to serversockaddr_insockAddr;memset(&sockAddr,0,sizeof(sockAddr));sockAddr.sin_family=AF_INET;//IPv4 addressinet_pton(AF_INET,"127.0.0.1",&sockAddr.sin_addr);//LOCALHOST IP addresssockAddr.sin_port=htons(1234);//port numbercharbufferSend[BUF_SIZE]={0};charbufferRecv[BUF_SIZE]={0};while(1){//create server socketSOCKETclientSock=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);//IPv4 address, TCP protocolconnect(clientSock,(SOCKADDR*)&sockAddr,sizeof(SOCKADDR));printf("Input s string: ");gets_s(bufferSend);send(clientSock,bufferSend,strlen(bufferSend),0);//send data to serverrecv(clientSock,bufferRecv,BUF_SIZE,0);//receive data from serverprintf("string from server: %s\n",bufferRecv);closesocket(clientSock);//close client socketmemset(bufferSend,0,BUF_SIZE);memset(bufferRecv,0,BUF_SIZE);}//terminate use of ws2_32.dllWSACleanup();return0;}