在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
。注意:這個示例僅用于演示目的,沒有進行錯誤處理和優化。在實際應用中,你需要添加更多的功能,如多客戶端支持、消息廣播等。