C语言用UDP 实现局域网聊天程序源码
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include
#include
#include
#include
#include
#include
#include
#include
#define CLIENT_LOGIN 100
#define CLIENT_CHAT 200
#define CLIENT_QUIT 300
#define SERVER_CHA T 400
#define SERVER_QUIT 500
struct node
{
char name[20];
struct sockaddr_in client_addr;
struct node *next;
};
struct message
{
long type;
char name[20];
char mtext[512];
};
struct node *create_list(void);
void insert_list(struct node *, char *, struct sockaddr_in *);
void delete_list(struct node *, char *);
void recv_message(int , struct node *);
void send_message(int , struct sockaddr_in *, pid_t );
void client_login(int , struct node *, struct message *, struct sockaddr_in *); void client_chat(int , struct node *, struct message *);
void client_quit(int , struct node *, struct message *);
void server_chat(int , struct node *, struct message *);
void server_quit(int , struct node *, struct message *);
void brocast_msg(int , struct node *, struct message *);
void father_func(int sig_no)
{
return ;
}
int main(int argc, const char *argv[])
{
int socket_fd;
pid_t pid;
struct sockaddr_in server_addr;
struct node *head;
if (argc < 3)
{
fprintf(stderr, "usages : %s ip port\n", argv[0]);
exit(-1);
}
if ((socket_fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
{
perror("failed to create socket");
exit(-1);
}
head = create_list();
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(atoi(argv[2]));
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
if (bind(socket_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
perror("failed to bind");
exit(-1);
}
if ((pid = fork()) < 0) //创建子经常
{
perror("failed to fork pid");
exit(-1);
}
if (pid == 0)
recv_message(socket_fd, head);
else
send_message(socket_fd, &server_addr, pid);
return 0;
}
struct node *create_list(void)
{
struct node *head;
head = (struct node *)malloc(sizeof(struct node));
head->next = NULL;
return head;
}
void insert_list(struct node *head, char *name, struct sockaddr_in *client_addr) {
struct node *new;
new = (struct node *)malloc(sizeof(struct node));
strcpy(new->name, name);
new->client_addr = *client_addr;
new->next = head->next;
head->next = new;
return ;
}
void delete_list(struct node *head, char *name)
{
struct node *p = head->next;
struct node *q = head;
while (p != NULL)
{
if (strcmp(p->name, name) == 0)
break;
p = p->next;