// https://e-penguiner.com/socket-programming-c-cpp/// オリジナルのsingle request power down pattern を改変してループとした
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>
int main(int argc, char const *argv[])
{
const int port_number = 12345;
// create server socket
int sockfd = 0;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// setup server socket
struct sockaddr_in server;
int addrlen = sizeof(server);
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("192.168.3.14");
server.sin_port = htons(port_number);
int opt = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
if (bind(sockfd, (struct sockaddr *)&server, sizeof(server)) < 0)
{
perror("Bind error");
exit(EXIT_FAILURE);
} // これでsockfdがサーバとなる
// start to listen requests
if (listen(sockfd, SOMAXCONN) < 0)
{
perror("Listen error");
exit(EXIT_FAILURE);
}
// accept request from client
struct sockaddr_in client;
int client_len = sizeof(client);
int sock = 0;
if ((sock = accept(sockfd, (struct sockaddr *)&client, (socklen_t *)&client_len)) < 0)
{
perror("Error: accept");
exit(EXIT_FAILURE);
} // listenしていてacceptしたら上記sockはクライアントをさす
// read data from client
char buff[1024] = {0};
while(1){
recv(sock, buff, sizeof(buff), 0);
printf("received message is \"%s\"\n", buff);
if (strncmp(buff,"on",2)==0) { printf("\nhi!light on!\n");}
// この関数で成功した!
// send data to client
char *hello = "Hello from server\n";
send(sock, hello, strlen(hello), 0);
printf("Message sent to client\n");
}
// close connecting socket
close(sock);
// close listening socket
shutdown(sockfd, SHUT_RDWR);
close(sockfd);
return 0;
}
0 件のコメント:
コメントを投稿