员工管理系统c语言服务器程序
时间: 2023-06-18 19:03:40 浏览: 63
c语言员工管理系统
3星 · 编辑精心推荐
员工管理系统的服务器程序可以使用C语言编写,以下是一个简单的实现示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8080
struct employee {
int id;
char name[50];
float salary;
};
int main(int argc, char const *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[1024] = {0};
char *hello = "Hello from server";
struct employee employees[3];
// initialize employees
employees[0].id = 1;
strcpy(employees[0].name, "John");
employees[0].salary = 5000.0;
employees[1].id = 2;
strcpy(employees[1].name, "Mary");
employees[1].salary = 6000.0;
employees[2].id = 3;
strcpy(employees[2].name, "Tom");
employees[2].salary = 7000.0;
// create server socket
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("socket failed");
exit(EXIT_FAILURE);
}
// set socket options
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt))) {
perror("setsockopt failed");
exit(EXIT_FAILURE);
}
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// bind socket to port
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// listen for connections
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// accept incoming connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// send welcome message
send(new_socket, hello, strlen(hello), 0);
printf("Hello message sent\n");
// receive client requests
while (1) {
valread = read(new_socket, buffer, 1024);
printf("%s\n", buffer);
if (strcmp(buffer, "list") == 0) {
// send list of employees
send(new_socket, employees, sizeof(employees), 0);
} else if (strcmp(buffer, "exit") == 0) {
// exit server
break;
} else {
// invalid command
send(new_socket, "Invalid command", strlen("Invalid command"), 0);
}
memset(buffer, 0, 1024);
}
close(new_socket);
close(server_fd);
return 0;
}
```
该服务器程序创建了一个socket,将其绑定到8080端口,并监听来自客户端的连接请求。一旦有连接请求,程序将接受连接并向客户端发送欢迎消息。随后,服务器程序将持续接收客户端的请求并根据请求发送相应的数据。在该示例中,如果客户端发送了"list"请求,服务器程序将发送员工列表;如果客户端发送了"exit"请求,服务器程序将退出。
阅读全文