在Linux环境下使用C举例实现一个局域网络聊天工具的编写,要求完成上线通知、下线通知、发送消息显示、单文件接收、单文件发送、显示在线用户名单等基本功能;利用UDP传送聊天信息,使用TCP传送文件数据。
时间: 2024-01-27 14:06:17 浏览: 123
实现一个局域网聊天工具需要涉及到网络编程、多线程编程、文件传输等知识。下面是一个简单的示例代码,仅供参考。
注:以下代码中使用了第三方库 cJSON,需要先进行安装。
1. 客户端代码 client.c:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <cjson/cJSON.h>
#define MAX_MSG_LEN 1024
#define MAX_USERNAME_LEN 32
#define MAX_FILENAME_LEN 64
// 消息类型
enum MessageType {
LOGIN,
LOGOUT,
CHAT,
FILE_REQUEST,
FILE_ACCEPT,
FILE_REJECT,
FILE_DATA,
FILE_FINISH
};
struct Message {
enum MessageType type;
char username[MAX_USERNAME_LEN];
char data[MAX_MSG_LEN];
int data_len;
};
struct FileRequest {
char filename[MAX_FILENAME_LEN];
int file_size;
};
// 服务器地址和端口号
char *server_ip = "127.0.0.1";
int server_port = 8888;
// 用户名
char username[MAX_USERNAME_LEN];
// UDP套接字和TCP套接字
int udp_sockfd;
int tcp_sockfd;
// 服务器地址
struct sockaddr_in server_addr;
// 线程处理函数:接收聊天消息
void *recv_chat_msg(void *arg) {
while (1) {
char buf[MAX_MSG_LEN];
struct sockaddr_in peer_addr;
socklen_t peer_addr_len = sizeof(peer_addr);
int len = recvfrom(udp_sockfd, buf, MAX_MSG_LEN - 1, 0, (struct sockaddr *)&peer_addr, &peer_addr_len);
if (len > 0) {
buf[len] = '\0';
cJSON *root = cJSON_Parse(buf);
if (root != NULL) {
cJSON *type = cJSON_GetObjectItem(root, "type");
if (type != NULL) {
if (strcmp(type->valuestring, "chat") == 0) {
cJSON *username = cJSON_GetObjectItem(root, "username");
cJSON *data = cJSON_GetObjectItem(root, "data");
if (username != NULL && data != NULL) {
printf("%s: %s\n", username->valuestring, data->valuestring);
}
} else if (strcmp(type->valuestring, "file_request") == 0) {
cJSON *filename = cJSON_GetObjectItem(root, "filename");
cJSON *file_size = cJSON_GetObjectItem(root, "file_size");
if (filename != NULL && file_size != NULL) {
printf("收到文件传输请求:%s(%d字节),是否接受?(输入Y或N)\n", filename->valuestring, file_size->valueint);
}
} else if (strcmp(type->valuestring, "file_accept") == 0) {
cJSON *filename = cJSON_GetObjectItem(root, "filename");
cJSON *port = cJSON_GetObjectItem(root, "port");
if (filename != NULL && port != NULL) {
struct sockaddr_in file_addr;
file_addr.sin_family = AF_INET;
file_addr.sin_addr.s_addr = htonl(INADDR_ANY);
file_addr.sin_port = htons(port->valueint);
if (bind(tcp_sockfd, (struct sockaddr *)&file_addr, sizeof(file_addr)) == 0) {
printf("正在发送文件%s...\n", filename->valuestring);
// 打开文件
int file_fd = open(filename->valuestring, O_RDONLY);
if (file_fd < 0) {
perror("打开文件失败");
continue;
}
// 发送文件数据
char file_buf[MAX_MSG_LEN];
int read_len;
while ((read_len = read(file_fd, file_buf, MAX_MSG_LEN)) > 0) {
int send_len = send(tcp_sockfd, file_buf, read_len, 0);
if (send_len != read_len) {
perror("发送文件数据失败");
close(file_fd);
close(tcp_sockfd);
return NULL;
}
}
// 关闭文件
close(file_fd);
// 发送文件传输结束消息
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "file_finish");
cJSON_AddStringToObject(root, "filename", filename->valuestring);
cJSON_AddStringToObject(root, "username", username);
char *json_str = cJSON_Print(root);
int send_len = sendto(udp_sockfd, json_str, strlen(json_str), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != strlen(json_str)) {
perror("发送文件传输结束消息失败");
}
free(json_str);
cJSON_Delete(root);
printf("文件%s发送完成\n", filename->valuestring);
} else {
perror("绑定TCP套接字失败");
}
}
} else if (strcmp(type->valuestring, "file_reject") == 0) {
cJSON *filename = cJSON_GetObjectItem(root, "filename");
if (filename != NULL) {
printf("文件%s传输被拒绝\n", filename->valuestring);
}
} else if (strcmp(type->valuestring, "file_data") == 0) {
cJSON *filename = cJSON_GetObjectItem(root, "filename");
cJSON *data = cJSON_GetObjectItem(root, "data");
if (filename != NULL && data != NULL) {
int write_len = write(tcp_sockfd, data->valuestring, data->valueint);
if (write_len != data->valueint) {
perror("写文件数据失败");
}
}
} else if (strcmp(type->valuestring, "file_finish") == 0) {
cJSON *filename = cJSON_GetObjectItem(root, "filename");
cJSON *username = cJSON_GetObjectItem(root, "username");
if (filename != NULL && username != NULL) {
printf("文件%s接收完成\n", filename->valuestring);
}
}
}
cJSON_Delete(root);
}
}
}
}
// 线程处理函数:接收文件数据
void *recv_file_data(void *arg) {
int file_fd = *(int *)arg;
char buf[MAX_MSG_LEN];
int len;
while ((len = recv(tcp_sockfd, buf, MAX_MSG_LEN, 0)) > 0) {
int write_len = write(file_fd, buf, len);
if (write_len != len) {
perror("写文件数据失败");
break;
}
}
close(file_fd);
close(tcp_sockfd);
}
// 发送聊天消息
void send_chat_msg(char *msg) {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "chat");
cJSON_AddStringToObject(root, "username", username);
cJSON_AddStringToObject(root, "data", msg);
char *json_str = cJSON_Print(root);
int send_len = sendto(udp_sockfd, json_str, strlen(json_str), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != strlen(json_str)) {
perror("发送聊天消息失败");
}
free(json_str);
cJSON_Delete(root);
}
// 发送文件传输请求
void send_file_request(char *filename, int file_size) {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "file_request");
cJSON_AddStringToObject(root, "username", username);
cJSON_AddStringToObject(root, "filename", filename);
cJSON_AddNumberToObject(root, "file_size", file_size);
char *json_str = cJSON_Print(root);
int send_len = sendto(udp_sockfd, json_str, strlen(json_str), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != strlen(json_str)) {
perror("发送文件传输请求失败");
}
free(json_str);
cJSON_Delete(root);
}
// 发送文件传输接受消息
void send_file_accept(char *filename, int port) {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "file_accept");
cJSON_AddStringToObject(root, "username", username);
cJSON_AddStringToObject(root, "filename", filename);
cJSON_AddNumberToObject(root, "port", port);
char *json_str = cJSON_Print(root);
int send_len = sendto(udp_sockfd, json_str, strlen(json_str), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != strlen(json_str)) {
perror("发送文件传输接受消息失败");
}
free(json_str);
cJSON_Delete(root);
}
// 发送文件传输拒绝消息
void send_file_reject(char *filename) {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "file_reject");
cJSON_AddStringToObject(root, "username", username);
cJSON_AddStringToObject(root, "filename", filename);
char *json_str = cJSON_Print(root);
int send_len = sendto(udp_sockfd, json_str, strlen(json_str), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != strlen(json_str)) {
perror("发送文件传输拒绝消息失败");
}
free(json_str);
cJSON_Delete(root);
}
// 发送文件传输数据
void send_file_data(char *filename, char *data, int data_len) {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "file_data");
cJSON_AddStringToObject(root, "username", username);
cJSON_AddStringToObject(root, "filename", filename);
cJSON_AddStringToObject(root, "data", data);
cJSON_AddNumberToObject(root, "data_len", data_len);
char *json_str = cJSON_Print(root);
int send_len = sendto(udp_sockfd, json_str, strlen(json_str), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != strlen(json_str)) {
perror("发送文件传输数据失败");
}
free(json_str);
cJSON_Delete(root);
}
// 发送文件传输结束消息
void send_file_finish(char *filename) {
cJSON *root = cJSON_CreateObject();
cJSON_AddStringToObject(root, "type", "file_finish");
cJSON_AddStringToObject(root, "username", username);
cJSON_AddStringToObject(root, "filename", filename);
char *json_str = cJSON_Print(root);
int send_len = sendto(udp_sockfd, json_str, strlen(json_str), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != strlen(json_str)) {
perror("发送文件传输结束消息失败");
}
free(json_str);
cJSON_Delete(root);
}
int main(int argc, char *argv[]) {
// 创建UDP套接字
udp_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (udp_sockfd < 0) {
perror("创建UDP套接字失败");
exit(1);
}
// 创建TCP套接字
tcp_sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (tcp_sockfd < 0) {
perror("创建TCP套接字失败");
exit(1);
}
// 设置服务器地址
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(server_ip);
server_addr.sin_port = htons(server_port);
// 获取用户名
printf("请输入用户名:");
fgets(username, MAX_USERNAME_LEN, stdin);
username[strlen(username) - 1] = '\0';
// 发送登录消息
struct Message msg;
msg.type = LOGIN;
strcpy(msg.username, username);
msg.data_len = 0;
int send_len = sendto(udp_sockfd, &msg, sizeof(msg), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != sizeof(msg)) {
perror("发送登录消息失败");
exit(1);
}
// 创建接收聊天消息的线程
pthread_t tid;
pthread_create(&tid, NULL, recv_chat_msg, NULL);
// 输入聊天消息
char input_buf[MAX_MSG_LEN];
while (1) {
fgets(input_buf, MAX_MSG_LEN, stdin);
if (input_buf[strlen(input_buf) - 1] == '\n') {
input_buf[strlen(input_buf) - 1] = '\0';
}
if (strcmp(input_buf, "quit") == 0) {
// 发送退出消息
struct Message msg;
msg.type = LOGOUT;
strcpy(msg.username, username);
msg.data_len = 0;
int send_len = sendto(udp_sockfd, &msg, sizeof(msg), 0, (struct sockaddr *)&server_addr, sizeof(server_addr));
if (send_len != sizeof(msg)) {
perror("发送退出消息失败");
}
break;
} else if (strncmp(input_buf, "send ", 5) == 0) {
// 发送文件
char filename[MAX_FILENAME_LEN];
int file_size;
if (sscanf(input_buf + 5, "%s %d", filename, &file_size) == 2) {
// 发送文件传输请求
send_file_request(filename, file_size);
// 接收文件传输接受或拒绝消息
fd_set rfds;
struct timeval tv;
FD_ZERO(&rfds);
FD_SET(STDIN_FILENO, &rfds);
tv.tv_sec = 5;
tv.tv_usec = 0;
int ret = select(STDIN_FILENO + 1, &rfds, NULL, NULL, &tv);
if (ret == -1) {
perror("select() error");
} else if (ret) {
char accept_buf[MAX_MSG_LEN];
fgets(accept_buf, MAX_MSG_LEN, stdin);
if (accept_buf[strlen(accept_buf) - 1] == '\n') {
accept_buf[strlen(accept_buf) - 1] = '\0';
}
if (strcmp(accept_buf, "Y") == 0) {
// 发送文件传输接受消息
struct sockaddr_in peer_addr;
socklen_t peer_addr_len = sizeof(peer_addr);
getpeername(udp_sockfd, (struct sockaddr *)&peer_addr, &peer_addr_len);
int port = ntohs(peer_addr.sin_port) + 1;
send_file_accept(filename, port);
// 连接TCP服务器
server_addr.sin_port = htons(port);
if (connect(tcp_sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == 0) {
// 打开文件
int file_fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
if (file_fd < 0) {
perror("打开文件失败");
continue;
}
// 创建接收文件数据的线程
pthread_t tid;
pthread_create(&tid, NULL, recv_file_data, &file_fd);
// 发送文件数据
char file_buf[MAX_MSG_LEN];
int read_len;
while ((read_len = read(tcp_sockfd, file_buf, MAX_MSG_LEN)) > 0) {
send_file_data(filename, file_buf, read_len);
}
// 等待接收文件传输结束消息
while (1) {
char buf[MAX_MSG_LEN];
struct sockaddr_in peer_addr;
socklen_t peer_addr_len = sizeof(peer_addr);
int len = recvfrom(udp_sockfd, buf, MAX_MSG_LEN - 1, 0, (struct sockaddr *)&peer_addr, &peer_addr_len);
if (len > 0) {
buf[len] = '\0';
cJSON *root = cJSON_Parse(buf);
if (root != NULL) {
cJSON *type = cJSON_GetObjectItem(root, "type");
cJSON *username = cJSON_GetObjectItem(root, "username");
cJSON *filename = cJSON_GetObjectItem(root, "filename");
if (type != NULL && username != NULL && filename != NULL && strcmp(type->valuestring, "file_finish") == 0 && strcmp(username->valuestring, username) == 0 && strcmp(filename->valuestring, filename) == 0) {
break;
}
cJSON_Delete(root);
}
}
}
// 发送文件传输结束消息
send_file_finish(filename);
// 等待接收线程结束
pthread_join(tid, NULL);
// 关闭文件
close(file_fd);
} else {
perror("连接TCP服务器失败");
}
} else {
// 发送文件传输拒绝消息
send_file_reject(filename);
}
} else {
printf("文件传输请求超时\n");
}
}
} else {
send_chat_msg(input_buf);
}
}
// 关闭套接字
close(udp_sockfd);
close(tcp_sockfd);
return 0;
}
```
2. 服务器端代码 server.c:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <fcntl.h>
#include <cjson/cJSON.h>
#define MAX_MSG_LEN 1024
#define MAX_USERNAME_LEN 32
#define MAX_FILENAME_LEN 64
// 消息类型
enum MessageType {
LOGIN,
LOGOUT,
CHAT,
FILE_REQUEST,
FILE_ACCEPT,
FILE_REJECT,
FILE_DATA,
FILE_FINISH
阅读全文