服务器
#include<myhead.h>
#define SER_PORT 8888
#define SER_IP "192.168.122.77"
//聊天室服务器端
//链表结构体
typedef struct Node
{
char name;
struct sockaddr_in cin;
struct Node *next;
}*lb;
/*
//创建链表函数
lb chuang()
{
lb p=(lb)malloc(sizeof(struct Node));
if(NULL ==p)
{
return NULL;
}
p->name=0;
p->next=NULL;
return p;
}
//尾插函数
lb cha(lb head,char mz,(struct sockaddr*)&cin)
{
lb s=chuang();
if(NULL ==s)
{
return head;
}
s->name=mz;
s->cin=cin;
if(NULL ==head)
{
head=s;
}
else
{
lb p=head;
while(p->next!=NULL)
{
p=p->next;
}
p->next=s;
}
return head;
}
//任意元素删除
lb shan(lb head,char mz)
{
lb p=head;
lb d=head;
while(p->next->name!=mz)
{
if(p->next ==NULL)
{
printf("已下线");
return head;
}
p=p->next;
}
d=p->next;
p->next=d->next;
free(d);
d=NULL;
return head;
}
*/
/******************主程序****************************/
int main(int argc, const char *argv[])
{
//创建套接字
int sfd=socket(AF_INET,SOCK_DGRAM,0);
if(sfd ==-1)
{
perror("socket error");
return -1;
}
//定义结构体变量存放服务器信息
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(SER_PORT);
sin.sin_addr.s_addr=inet_addr(SER_IP);
//绑定
if(bind(sfd,(struct sockaddr*)&sin,sizeof(sin)) ==-1)
{
perror("bind error");
return -1;
}
//定义结构体变量存放客户端信息
struct sockaddr_in cin;
socklen_t socklen=sizeof(cin);
char name[128]="";
char buf[128]="";
//接收名字
recvfrom(sfd,name,sizeof(name),0,(struct sockaddr*)&cin,&socklen);
printf("%s:已经上线\n",name);
/*
//创建链表
lb p=chuang();
p->mz=name;
p->cin=cin;
*/
while(1)
{
bzero(buf,sizeof(buf));
recvfrom(sfd,buf,sizeof(buf),0,(struct sockaddr*)&cin,&socklen);
buf[strlen(buf)-1]=0;
if(strcmp(buf,"quit") ==0)
{
strcat(name,"已经下线");
sendto(sfd,name,sizeof(name),0,(struct sockaddr*)&cin,sizeof(cin));
}
else
{
strcat(name,buf);
sendto(sfd,name,sizeof(buf),0,(struct sockaddr*)&cin,sizeof(cin));
}
}
close(sfd);
return 0;
}
客户端
#include<myhead.h>
#define SER_PORT 8888
#define SER_IP "192.168.122.77"
//聊天室客户端
int main(int argc, const char *argv[])
{
//创建套接字
int cfd=socket(AF_INET,SOCK_DGRAM,0);
if(cfd ==-1)
{
perror("socket error");
return -1;
}
//定义结构体变量存放服务器信息
struct sockaddr_in sin;
sin.sin_family=AF_INET;
sin.sin_port=htons(SER_PORT);
sin.sin_addr.s_addr=inet_addr(SER_IP);
//数据传输
char buf[128]="";
printf("请输入你的名字:");
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
sendto(cfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,sizeof(sin));
while(1)
{
bzero(buf,sizeof(buf));
fgets(buf,sizeof(buf),stdin);
buf[strlen(buf)-1]=0;
if(strcmp(buf,"quit") ==0)
{
sendto(cfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,sizeof(sin));
break;
}
sendto(cfd,buf,sizeof(buf),0,(struct sockaddr*)&sin,sizeof(sin));
recvfrom(cfd,buf,sizeof(buf),0,NULL,NULL);
printf("%s\n",buf);
}
close(cfd);
return 0;
}