基于tcp协议的简易聊天机器人使用C语言
时间: 2023-12-13 16:05:59 浏览: 106
好的,下面我将给出一个基于TCP协议的简易聊天机器人C语言示例代码,希望能帮到您:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#define PORT 8888
#define MAX_MSG_SIZE 1024
int main()
{
int server_fd, new_socket, valread;
struct sockaddr_in address;
int opt = 1;
int addrlen = sizeof(address);
char buffer[MAX_MSG_SIZE] = {0};
char *hello = "Hello from server";
// 创建TCP套接字
if ((server_fd = socket(AF_INET, SOCK_STREAM, 0)) == 0)
{
perror("socket failed");
exit(EXIT_FAILURE);
}
// 设置套接字选项
if (setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt)))
{
perror("setsockopt");
exit(EXIT_FAILURE);
}
// 初始化服务器地址
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);
}
// 监听连接
if (listen(server_fd, 3) < 0)
{
perror("listen");
exit(EXIT_FAILURE);
}
// 等待连接
if ((new_socket = accept(server_fd, (struct sockaddr *)&address, (socklen_t*)&addrlen))<0)
{
perror("accept");
exit(EXIT_FAILURE);
}
// 向客户端发送欢迎消息
send(new_socket, hello, strlen(hello), 0 );
printf("Hello message sent\n");
// 循环等待客户端发送消息
while (1)
{
memset(buffer, 0, MAX_MSG_SIZE);
valread = read(new_socket, buffer, MAX_MSG_SIZE);
printf("Client: %s", buffer);
// 根据客户端发送的消息,给出回复
if (strcmp(buffer, "Hello\n") == 0)
{
printf("Server: Hi there!\n");
send(new_socket, "Hi there!", strlen("Hi there!"), 0);
}
else if (strcmp(buffer, "How are you?\n") == 0)
{
printf("Server: I'm fine, thank you!\n");
send(new_socket, "I'm fine, thank you!", strlen("I'm fine, thank you!"), 0);
}
else if (strcmp(buffer, "Quit\n") == 0)
{
printf("Server: Goodbye!\n");
send(new_socket, "Goodbye!", strlen("Goodbye!"), 0);
break;
}
else
{
printf("Server: Sorry, I don't understand.\n");
send(new_socket, "Sorry, I don't understand.", strlen("Sorry, I don't understand."), 0);
}
}
// 关闭套接字
close(new_socket);
close(server_fd);
return 0;
}
```
这个示例代码创建了一个TCP服务器程序,等待客户端连接,并根据预先设定好的回复规则,与客户端进行交互。当收到客户端发送的消息后,服务器会根据预先设定好的回复规则,给客户端发送回复。当客户端发送“Quit”消息时,服务器会关闭连接。在实际应用中,可以根据需要修改回复规则和相关参数。
阅读全文