C/C++ code/*
*
* server
*
* */
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#define SERVPORT 1234
#define BACKLOG 20
#define MAX_CON_NO 10
#define MAX_DATA_SIZE 5
int main() {
struct sockaddr_in serverSockaddr, clientSockaddr;
int sinSize, recvBytes;
int sockfd, clientfd;
char buf[MAX_DATA_SIZE];
/*establish a socket*/
if((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror("fail to establish a socket");
exit(1);
}
printf("Success to establish a socket...(sockfd = %d)\n", sockfd);
/*init sockaddr_in*/
serverSockaddr.sin_family = AF_INET;
serverSockaddr.sin_port = htons(SERVPORT);
serverSockaddr.sin_addr.s_addr = INADDR_ANY;
bzero(&(serverSockaddr.sin_zero), 8);
/*bind socket*/
if(bind(sockfd, (struct sockaddr *)&serverSockaddr, sizeof(struct sockaddr))== -1) {
perror("fail to bind");
exit(1);
}
printf("Success to bind the socket...\n");
/*listen on the socket*/
if(listen(sockfd, BACKLOG) == -1) {
perror("fail to listen");
exit(1);
}
printf("Success to listen on the socket...\n");
/*accept a client's request*/
if((clientfd = accept(sockfd, (struct sockaddr *)&clientSockaddr, &sinSize)) == -1) {
perror("fail to acceot");
exit(1);
}
printf("Success to accpet...\n");
/*call recv to receive datas*/
if((recvBytes = recv(sockfd, buf, MAX_DATA_SIZE, 0)) == -1) {
perror("fail to receive datas");
exit(1);
}
printf("Receive a connection:%s \n", buf);
close(sockfd);
}