Experiment 2 connection oriented Socket programming
1, Experimental purpose
1. Understand the working principle, service mode and type of Socket.
2. Understand the framework structure and related data structure of Socket application.
3. Understand the connection oriented Socket communication process.
4. Master the method of using WinSock function to write connection oriented network application.
2, Experiment contents and requirements
1. Write TCP socket based server application TcpServer on Windows platform. The server receives the message sent by the client, displays the source, time and content of the received message, and sends back the information to the client for reception confirmation.
2. Write TCP socket based client application TcpClient on Windows platform. The client program actively initiates the connection with the server program, reads the information entered by the user, sends it to the server, and receives the feedback information from the server.
3. Run TcpServer and TcpClient on the same or different computers to test the sending and receiving of messages. It is required that after the connection is established, the client can send messages to the server several times in a row.
4. Use Windows commands to view TCP connection information and process information of TcpServer and TcpClient respectively.
3, Experimental principle
On the server side, the server starts up first and calls socket() to create a socket; Then call bind() to bind the address of server (IP%+port). Then call listen() to prepare the server for listening and specify the length of the request queue. Then the server enters the blocking state and waits for the connection request of the client; Finally, accept() is used to receive the connection request and obtain the address of the client. When accpet receives a connect request from a client, it will generate a new socket for data transmission.
On the client side, the client creates a socket and specifies the socket address of the client, and then calls connect() to establish a connection with the server. Once the connection is established successfully, the client and server can receive and send data by calling recv and send. Once the data transfer is completed, the server and client close the socket by calling close().
Connection oriented Socket communication process.
The server
① Header files and constant definitions
② Declare variable
③ Initialize Socket environment
④ Create a Socket for listening
⑤ Set the server Socket address
⑥ Bind Sockets Server to local address
⑦ Listen on the Socket Server
⑧ Accept requests from clients
⑨ Send and receive data between the server and the client ⑩ release resources
client
① Header files and constant definitions
② Declare variable
③ Initialize Socket environment
④ Create a Socket for communication
⑤ Set the server Socket address
⑥ Connect to server
⑦ Send and receive data between the server and the client
⑧ Release resources
4, Experimental steps
5, Experimental summary
Attachment: program source code
client
#include "stdafx.h" #include <string> #include<iostream> #include<winsock2.h> #pragma comment(lib,"WS2_32.lib") #define BUF_SIZE 64 / / buffer size int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsd; SOCKET sHost; SOCKADDR_IN servAddr; char buf[BUF_SIZE]; int retVal; //Initialize Windows Socket if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { printf("WSAStartup failed!\n"); return 1; } //Create socket sHost = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(INVALID_SOCKET == sHost) { printf("socket failed!\n"); WSACleanup(); return -1; } //Set server address servAddr.sin_family = AF_INET; servAddr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1"); //The user should modify it according to the actual situation servAddr.sin_port = htons(9990); //In practical application, it is recommended to save the IP address and port number of the server in the configuration file int sServerAddlen = sizeof(servAddr); //Calculate the length of the address //Connect server printf("TcpClient trying to connect to TcpServer...\n"); retVal = connect(sHost,(LPSOCKADDR)&servAddr,sizeof(servAddr)); if(SOCKET_ERROR == retVal) { printf("Connect to TcpServer failed !\n"); closesocket(sHost); WSACleanup(); system("pause"); return -1; } else { printf("Connected to TcpServer success...\n"); } Send data to server //ZeroMemory(buf,BUF_SIZE); //sprintf(buf,"Data form TcpClient!"); //retVal = send(sHost,buf,strlen(buf),0); //if(SOCKET_ERROR == retVal) //{ //printf("send failed!\n"); //closesocket(sHost); //WSACleanup(); //return -1; //} //printf("client data sending completed! \ n"); //Send and receive data between client and server //Loop to send a string to the server and display feedback //Sending "quit" will exit the server program and the client program itself while (true) { //Send data to server printf("Please input a string to send :"); std::string str; //Receive input data std::getline(std::cin,str); //Copy the data entered by the user into buf ZeroMemory(buf,BUF_SIZE); strcpy(buf,str.c_str()); //Send data to server retVal = send(sHost,buf,strlen(buf),0); if(SOCKET_ERROR == retVal) { printf("send failed!\n"); closesocket(sHost); WSACleanup(); return -1; } //Receive the data returned by the server retVal == recv(sHost,buf,sizeof(buf)+1,0); printf("Recv Form Server:%s\n",buf); //If "quit" is received, exit if(strcmp(buf,"quit") == 0) { printf("quit!\n"); break; } } //Release resources closesocket(sHost); WSACleanup(); }
The server
#include "stdafx.h" #include<iostream> #include<winsock2.h> #pragma comment(lib,"WS2_32.lib") #define BUF_SIZE 64 / / buffer size int _tmain(int argc, _TCHAR* argv[]) { WSADATA wsd; SOCKET sServer; SOCKET sAccept; SOCKET sClient; int retVal; char buf[BUF_SIZE]; //A buffer used to accept client data //Initialize socket dynamic library if(WSAStartup(MAKEWORD(2,2),&wsd)!=0) { printf("WSAStartup failed !\n"); return 1; } printf("Server initialization succeeded!\n"); //Create socket for listening sServer = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(INVALID_SOCKET == sServer) { printf("scoket failed!\n"); WSACleanup(); return -1; } printf("Server created listening socket successfully!\n"); //Set server socket address SOCKADDR_IN addrServ; addrServ.sin_family = AF_INET; addrServ.sin_port = htons(9990); //The listening port is 9990 addrServ.sin_addr.S_un.S_addr = htonl(INADDR_ANY); //Bind socket sServer to local address, port 9990 retVal = bind(sServer,(const struct sockaddr*)&addrServ,sizeof(SOCKADDR_IN)); if(SOCKET_ERROR == retVal) { printf("bind failed !\n"); closesocket(sServer); WSACleanup(); return -1; } printf("Server socket address binding succeeded!\n"); //listening socket retVal = listen(sServer,3); if(SOCKET_ERROR == retVal) { printf("listen failed !\n"); closesocket(sServer); WSACleanup(); return -1; } printf("The server is already listening!\n"); //Accept customer requests sockaddr_in addrAccept; //Client address int addrAcceptlen = sizeof(addrAccept); sAccept = accept(sServer,(sockaddr FAR*)&addrAccept,&addrAcceptlen); if(INVALID_SOCKET == sAccept) { printf("accept failed:%d!\n",GetLastError()); closesocket(sServer); WSACleanup(); return -1; } //printf("the server has established a connection with a client... \ n"); //printf("server starts receiving client data... \ n"); //ZeroMemory(buf,BUF_SIZE); // Clear buffer for receiving data //retVal=recv(sAccept,buf,BUF_SIZE,0); // Note not buf_ Size, but BUFSIZE //if (SOCKET_ERROR == retVal) //{ // printf("recv failed !\n"); // closesocket(sAccept); // closesocket(sServer); // WSACleanup(); // return -1; //} //printf("Recv Form Client [%s:%d]:%s\n",inet_ntoa(addrAccept.sin_addr),addrAccept.sin_port,buf); //Sending and receiving data between server and client //Receive the client's data circularly, and exit after sending the quit command directly to the client while (true) { ZeroMemory(buf,BUF_SIZE); //Clear buffer for receiving data retVal = recv(sClient,buf,BUFSIZ,0); if(SOCKET_ERROR == retVal) { printf("recv failed!\n"); closesocket(sServer); closesocket(sClient); WSACleanup(); return -1; } //Get current system time SYSTEMTIME st; GetLocalTime(&st); char sDateTime[30]; sprintf(sDateTime,"%4d-%2d-%2d %2d:%2d:%2d",st.wYear,st.wMonth,st.wDay,st.wHour,st.wMinute,st.wSecond); //Printout information printf("%s,Recv Form Client [%s:%d]:%s\n",sDateTime,inet_ntoa(addrAccept.sin_addr),addrAccept.sin_port,buf); //If the client sends the "quit" string, the server exits if(strcmp(buf,"quit") == 0) { retVal = send(sClient,"quit",strlen("quit"),0); break; } //Otherwise, an echo string is sent to the client else{ char msg[BUF_SIZE]; sprintf(msg,"Message received - %s",buf); retVal = send(sClient,msg,strlen(msg),0); //Send echo string to client if(SOCKET_ERROR == retVal) { printf("send failed!\n"); closesocket(sServer); closesocket(sClient); WSACleanup(); return -1; } } } //Release socket closesocket(sAccept); closesocket(sServer); WSACleanup(); system("pause"); return 0; }