转自:http://kakadu.blog.51cto.com/4050768/828015
小例子代码实现了基于udp 的socket通信。完成的功能如下:
1、 利用socket编程建立服务器与客户端之间的UDP连接。
2、 完成C/S之间的数据通信,具体包括4点:
① Client通过给定的Server IP和端口号向Server端发送请求。请求来自cmd命令行用户输入。
② Server端保持监听状态,收到Client端请求后,将请求内容输出到命令行。
③ Server端每接收一次请求数据,即向发出请求的客户端发送“OK”字符串,表示该请求已经Received。
④ Client端接收到“OK”字符串后即将其输出到命令行。
服务器端代码如下:
- //chang. exercise of UDP socket.
- // Implements the function of send info between server and client.
- //When this server is listening and a client send an request, it's will print the info on the cmd and reply a data:"OK".
- //server.
- #include "stdio.h"
- #include "Winsock2.h"
- #include "iostream"
- #include "string"
- //should add the under line if not add lib in the project.(appendicular dependent)
- //#pragma comment(lib, "ws2_32.lib")
- //define host IP and usable port.
- #define HOST_IP 127.0.0.1
- #define HOST_PORT 8080
- #define OK_STR "OK"
- void main(){
- //the version bit of Winsock
- int version_a = 1;//low bit
- int version_b = 1;//high bit
- //makeword
- WORD versionRequest = MAKEWORD(version_a,version_b);
- WSAData wsaData;
- int err;
- //wsa startup
- err = WSAStartup(versionRequest, &wsaData);
- if(err != 0 ){
- printf("ERROR!");
- return;
- }
- //check whether the version is 1.1, if not print the error and cleanup wsa?
- if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
- {
- printf("WRONG WINSOCK VERSION!");
- WSACleanup();
- return;
- }
- /*
- *build the socket
- *first param is protocol family, generally AF_INET for IP internet.
- *second param is type of socket, SOCK_DGRAM is for Data Gram(UDP), and SOCK_STREAM is for TCP.
- *the last param is communicate protocol. Generally is zero.
- */
- SOCKET socServer = socket(AF_INET, SOCK_DGRAM,0);
- //infomation of address, always NOT being operated directly.
- SOCKADDR_IN addr_Srv;
- //Struct sin_addr is used to defind IP address, it's a property of addr_in.
- //It's nest three structs as S_un_b, S_un_w and S-un.(union)
- addr_Srv.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
- //set protocol family
- addr_Srv.sin_family = AF_INET;
- //set host port
- addr_Srv.sin_port = htons(HOST_PORT);
- //bind socket to the host
- bind(socServer,( SOCKADDR*) &addr_Srv, sizeof(SOCKADDR));
- //address of a client
- SOCKADDR_IN addr_Clt;
- char recvBuf[100];
- int fromlen = sizeof(SOCKADDR);
- // while() to listen all the time
- while(true){
- //receive data function of server
- recvfrom(socServer, recvBuf, 100, 0, (SOCKADDR*) &addr_Clt, &fromlen);
- //output the data received to cmd
- std::cout<<recvBuf<<std::endl;
- //send "OK" to the from_client to indicates that data have been received.
- //send function is used by server, while sendto function is used by client. NOT sure.
- // send(addr_Clt, OK_STR, strlen(OK_STR)+1, 0);
- sendto(socServer, OK_STR, strlen(OK_STR)+1, 0, (SOCKADDR*)&addr_Clt, sizeof(SOCKADDR));
- }
- // at last close the socket.
- closesocket(socServer);
- //cleanup WSAData
- WSACleanup();}
客户端代码如下:
- //chang. exercise of UDP socket.
- // Implements the function of send info between server and client.
- //When this server is listening and a client send an request, it's will print the info on the cmd and reply a data:"OK".
- //client.
- #include "Winsock2.h"
- #include "iostream"
- #include "stdio.h"
- #pragma comment(lib, "ws2_32.lib")
- #define HOST_IP "127.0.0.1"
- #define HOST_PORT 8080
- void main(){
- //the version bit of Winsock
- int version_a = 1;//low bit
- int version_b = 1;//high bit
- //makeword
- WORD versionRequest = MAKEWORD(version_a,version_b);
- WSAData wsaData;
- int error;
- error = WSAStartup(versionRequest, &wsaData);
- if(error != 0 ){
- printf("ERROR!");
- return;
- }
- //check whether the version is 1.1, if not print the error and cleanup wsa?
- if (LOBYTE(wsaData.wVersion) != 1 || HIBYTE(wsaData.wVersion) != 1)
- {
- printf("WRONG WINSOCK VERSION!");
- WSACleanup();
- return;
- }
- //request info obtained by user's input
- char requestStr[100];
- //build a sockeet
- SOCKET socClient = socket(AF_INET, SOCK_DGRAM, 0);
- SOCKADDR_IN addrSrv; // a instance of SOCKADDR_IN, which is used in format of SOCKADDR.
- addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1"); //set the host IP
- addrSrv.sin_family=AF_INET; //set the protocol family
- addrSrv.sin_port=htons(HOST_PORT); //set the port number
- // array to store the data that server feedback.
- char cRecvBuf[100];
- // int len=sizeof(SOCKADDR);
- //while
- while(true){
- // gain info that user input
- std::cin>>requestStr;
- //sendto function is used to send programe data to the server
- sendto(socClient, requestStr, strlen(requestStr)+1, 0, (SOCKADDR*) &addrSrv, sizeof(SOCKADDR));
- //receive the feedback info from server
- //recv function is used in client.
- recv(socClient, cRecvBuf, strlen(cRecvBuf)+1, 0);
- //output the cRecvBuf to cmd
- std::cout<< cRecvBuf << std::endl;
- }
- //close the socket and cleanup the wsadata
- closesocket(socClient);
- WSACleanup();
- // return 0;
- }