用C语言TCP套接字编写关于员工管理系统的查询员工信息功能的具体代码
时间: 2024-02-05 22:11:50 浏览: 70
以下是一个简单的基于TCP套接字的员工管理系统查询员工信息的服务器端代码示例,使用C语言编写:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#define PORT 8080
#define MAX_CONNECTIONS 5
#define MAX_BUFFER_SIZE 1024
typedef struct {
int id;
char name[50];
int age;
char department[50];
} Employee;
Employee employees[] = {
{1, "John Doe", 30, "Sales"},
{2, "Jane Smith", 25, "Marketing"},
{3, "Bob Johnson", 40, "IT"},
{4, "Mary Lee", 35, "HR"},
};
int main(int argc, char *argv[]) {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[MAX_BUFFER_SIZE] = {0};
char response[MAX_BUFFER_SIZE] = {0};
// Create socket file descriptor
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0) {
perror("Socket creation 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);
}
// Set address
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
// Bind socket to address
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("Bind failed");
exit(EXIT_FAILURE);
}
// Listen for connections
if (listen(server_fd, MAX_CONNECTIONS) < 0) {
perror("Listen failed");
exit(EXIT_FAILURE);
}
printf("Server started on port %d\n", PORT);
while (1) {
// Accept new connection
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen)) < 0) {
perror("Accept failed");
exit(EXIT_FAILURE);
}
// Read query from client
valread = read(new_socket, buffer, MAX_BUFFER_SIZE);
printf("Received query: %s\n", buffer);
// Parse query and search for employee
int id = atoi(buffer);
Employee *employee = NULL;
for (int i = 0; i < sizeof(employees) / sizeof(Employee); i++) {
if (employees[i].id == id) {
employee = &employees[i];
break;
}
}
// Generate response
if (employee) {
sprintf(response, "ID: %d\nName: %s\nAge: %d\nDepartment: %s\n", employee->id, employee->name, employee->age, employee->department);
} else {
sprintf(response, "Employee with ID %d not found\n", id);
}
// Send response to client
send(new_socket, response, strlen(response), 0);
printf("Sent response: %s\n", response);
// Close connection
close(new_socket);
}
return 0;
}
```
在本示例中,我们定义了一个名为`Employee`的结构体,以表示员工信息。我们定义了一些样本员工数据,在`main()`函数中,我们创建了一个TCP套接字并将其绑定到本地地址和端口`8080`上。我们使用`listen()`函数开始监听连接请求,等待客户端连接。
一旦客户端连接成功,我们使用`accept()`函数接受新的连接,并从客户端读取查询信息。然后,我们解析查询信息,并在员工列表中搜索具有相应ID的员工。如果找到员工,则生成响应字符串,否则生成“未找到员工”的字符串。最后,我们使用`send()`函数将响应字符串发送回客户端,并关闭连接。
注意:这只是一个简单的代码示例,实际的员工管理系统可能需要更复杂的查询逻辑和更复杂的数据存储方案。
阅读全文