在C语言中,实现一个简单的聊天程序可以通过套接字编程(socket programming)来完成。这里是一个基本的TCP聊天程序的例子,包括服务器端和客户端。
服务器端代码(server.c):
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int server_fd, client_fd;
struct sockaddr_in server_addr, client_addr;
socklen_t client_addr_size;
char buffer[BUFFER_SIZE];
// 创建套接字
server_fd = socket(AF_INET, SOCK_STREAM, 0);
if (server_fd == -1) {
perror("socket");
exit(1);
}
// 配置套接字
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(PORT);
// 绑定套接字
if (bind(server_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("bind");
exit(1);
}
// 监听连接
if (listen(server_fd, 1) == -1) {
perror("listen");
exit(1);
}
// 接受连接
client_addr_size = sizeof(client_addr);
client_fd = accept(server_fd, (struct sockaddr *)&client_addr, &client_addr_size);
if (client_fd == -1) {
perror("accept");
exit(1);
}
// 接收并发送消息
while (1) {
memset(buffer, 0, BUFFER_SIZE);
read(client_fd, buffer, BUFFER_SIZE);
printf("Client: %s\n", buffer);
memset(buffer, 0, BUFFER_SIZE);
fgets(buffer, BUFFER_SIZE, stdin);
write(client_fd, buffer, strlen(buffer));
}
// 关闭套接字
close(client_fd);
close(server_fd);
return 0;
}
客户端代码(client.c):
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8080
#define BUFFER_SIZE 1024
int main() {
int client_fd;
struct sockaddr_in server_addr;
char buffer[BUFFER_SIZE];
// 创建套接字
client_fd = socket(AF_INET, SOCK_STREAM, 0);
if (client_fd == -1) {
perror("socket");
exit(1);
}
// 配置套接字
memset(&server_addr, 0, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
server_addr.sin_port = htons(PORT);
// 连接服务器
if (connect(client_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
perror("connect");
exit(1);
}
// 接收并发送消息
while (1) {
memset(buffer, 0, BUFFER_SIZE);
fgets(buffer, BUFFER_SIZE, stdin);
write(client_fd, buffer, strlen(buffer));
memset(buffer, 0, BUFFER_SIZE);
read(client_fd, buffer, BUFFER_SIZE);
printf("Server: %s\n", buffer);
}
// 关闭套接字
close(client_fd);
return 0;
}
要编译和运行这些代码,请按照以下步骤操作:
server.c
和client.c
。gcc server.c -o server
和 gcc client.c -o client
。./server
。./client
。注意:这个示例仅用于演示目的,没有进行错误处理和优化。在实际应用中,你需要添加更多的功能,如多客户端支持、消息广播等。