c语言基于udp协议的简易聊天机器人客户端和服务器端代码
时间: 2023-11-28 15:51:38 浏览: 110
基于UDP协议的简易聊天机器人
4星 · 用户满意度95%
以下是基于UDP协议的简易聊天机器人客户端和服务器端的C语言代码。
客户端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8080
#define BUFFER_SIZE 1024
int main() {
// 创建UDP套接字
int client_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (client_socket < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 设置服务器地址
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(SERVER_PORT);
if (inet_pton(AF_INET, SERVER_IP, &server_address.sin_addr) <= 0) {
perror("invalid address");
exit(EXIT_FAILURE);
}
// 向服务器发送消息
char buffer[BUFFER_SIZE];
while (1) {
printf("Enter message: ");
fgets(buffer, BUFFER_SIZE, stdin);
if (strcmp(buffer, "exit\n") == 0) {
break;
}
sendto(client_socket, buffer, strlen(buffer), 0, (struct sockaddr*)&server_address, sizeof(server_address));
// 从服务器接收响应
memset(buffer, 0, BUFFER_SIZE);
socklen_t server_address_len = sizeof(server_address);
ssize_t received_bytes = recvfrom(client_socket, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&server_address, &server_address_len);
if (received_bytes < 0) {
perror("receive failed");
exit(EXIT_FAILURE);
}
printf("Server response: %s\n", buffer);
}
// 关闭套接字并退出
close(client_socket);
return 0;
}
```
服务器端代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8080
#define BUFFER_SIZE 1024
int main() {
// 创建UDP套接字
int server_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (server_socket < 0) {
perror("socket creation failed");
exit(EXIT_FAILURE);
}
// 绑定服务器地址
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_addr.s_addr = htonl(INADDR_ANY);
server_address.sin_port = htons(SERVER_PORT);
if (bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address)) < 0) {
perror("bind failed");
exit(EXIT_FAILURE);
}
// 接收来自客户端的消息并回复
char buffer[BUFFER_SIZE];
struct sockaddr_in client_address;
socklen_t client_address_len = sizeof(client_address);
while (1) {
memset(buffer, 0, BUFFER_SIZE);
ssize_t received_bytes = recvfrom(server_socket, buffer, BUFFER_SIZE, 0, (struct sockaddr*)&client_address, &client_address_len);
if (received_bytes < 0) {
perror("receive failed");
exit(EXIT_FAILURE);
}
printf("Client message: %s", buffer);
// 向客户端发送响应
char* response = "Hello, I am a chatbot!";
sendto(server_socket, response, strlen(response), 0, (struct sockaddr*)&client_address, client_address_len);
}
// 关闭套接字并退出
close(server_socket);
return 0;
}
```
请注意,本代码仅作为示例,未进行异常处理和数据验证。在实际应用中,需要根据需求进行相应的改进。
阅读全文