写一段使用C语言的socket编程实现服务器。首先需要在服务器端建立socket,然后监听端口,等待客户端连接。当esp8266连接服务器后,可以使用recv函数接收数据。接收到数据后,可以将数据存储到MySQL数据库中。可以使用C语言的MySQL API实现数据上传操作。
时间: 2023-05-31 14:07:26 浏览: 98
socket编程 实现服务器和客户的通信
5星 · 资源好评率100%
以下是使用C语言的socket编程实现服务器的代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <mysql/mysql.h>
#define PORT 8080
#define MAX_BUFFER_SIZE 1024
int main() {
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[MAX_BUFFER_SIZE] = {0};
MYSQL *mysql = mysql_init(NULL);
// Create a 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);
}
// Bind socket to a specific IP address and port number
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(PORT);
if (bind(server_fd, (struct sockaddr *)&address, sizeof(address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// Listen for incoming connections
if (listen(server_fd, 3) < 0) {
perror("listen failed");
exit(EXIT_FAILURE);
}
// Initialize MySQL connection
if (mysql_real_connect(mysql, "localhost", "username", "password", "database", 0, NULL, 0) == NULL) {
fprintf(stderr, "%s\n", mysql_error(mysql));
mysql_close(mysql);
exit(EXIT_FAILURE);
}
// Accept incoming connections
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t *)&addrlen)) < 0) {
perror("accept failed");
exit(EXIT_FAILURE);
}
// Receive data from the client and store it in the database
while (1) {
if ((valread = recv(new_socket, buffer, MAX_BUFFER_SIZE, 0)) <= 0) {
perror("recv failed");
exit(EXIT_FAILURE);
} else {
printf("Received data: %s", buffer);
// Insert data into the database
char query[MAX_BUFFER_SIZE];
sprintf(query, "INSERT INTO table_name (data) VALUES ('%s')", buffer);
if (mysql_query(mysql, query)) {
fprintf(stderr, "%s\n", mysql_error(mysql));
} else {
printf("Data inserted!\n");
}
}
memset(buffer, 0, sizeof(buffer)); // Clear the buffer
}
// Close connections
close(new_socket);
mysql_close(mysql);
return 0;
}
```
注意,在实际应用中,我们需要为MySQL数据库设置正确的IP地址、用户名、密码、数据库名称以及数据表名称。另外,上面的代码仅仅是演示如何将数据存储到MySQL数据库中,实际应用中,我们可能还需要对数据进行解析、处理等操作。
阅读全文