91av视频/亚洲h视频/操亚洲美女/外国一级黄色毛片 - 国产三级三级三级三级

資源簡介

Linux下基于UDP的socket編程,適用多客戶端之間,服務器與客戶端之間的通信。客戶端和服務端代碼分開了。notepad++可打開

資源截圖

代碼片段和文件信息

#include?
#include?
#include?
#include?

#include?
#include?
#include?
#include?
#include?
#include?“list.h“
#include?
#include?
#define?SIZE_BUFF?1024

//標識客戶端的結構體
struct?udp_client
{
//客戶端IP、端口信息
struct?sockaddr_in?cli;

//用于判斷客戶端是否在線的計數器,此計數器1s左右減一次
//減到0s代表客戶端斷開了連接(UDP客戶端30s沒有與服務器通信就認為斷開了)當有消息到來時該計數器置為30s.
unsigned?char?time_count;

//客戶端名字
char?name[50];

//其對端客戶端的節點地址
struct?udp_client?*target_node;

//內核鏈表
struct?list_head?kernel_list;
};
pthread_mutex_t?mutex;
void?*?delete_client(void?*p);
struct?udp_client?*?head;
struct?udp_client?*?get_node(struct?sockaddr_in?*cli);
int?main(void)
{

int?serfd?=?-1;
serfd?=?socket(AF_INETSOCK_DGRAM0);
if(serfd?<0)
{
perror(“socket“);
exit(1);
}

//設置服務器(本機)IP的端口
struct?sockaddr_in?ser;
bzero(&sersizeof(ser));

ser.sin_family?=?AF_INET;?
//端口為6666
ser.sin_port???=?htons(6666);
//IP為自動(本機網卡IP)
inet_pton(AF_INET“0.0.0.0“&ser.sin_addr);

if(bind(serfd(struct?sockaddr?*)&sersizeof(ser))<0)
{
perror(“bind“);
exit(1);
}

struct?sockaddr_in?cli;
bzero(&clisizeof(cli));
int?len?=?sizeof(cli);
char?buf[SIZE_BUFF];

int?ret?=-1;

//定義頭節點并申請空間
head?=?(struct?udp_client*)malloc(sizeof(struct?udp_client));

if(NULL?==?head)
{
perror(“malloc“);
exit(1);
}
//鏈表頭節點初始化
INIT_LIST_HEAD(&head->kernel_list);

//遍歷鏈表相關的定義
struct?list_head?*pos=NULL*n=NULL;
struct?udp_client*?p_max_struct;
pthread_mutex_init(&mutexNULL);
pthread_t?thread;
ret=pthread_create(&threadNULLdelete_clientNULL);
if(ret!=0)
{
perror(“pthread_creat“);
}
if(pthread_detach(thread)!=0)
{
perror(“pthread_detach“);
}

while(1)
{
bzero(bufSIZE_BUFF);
//接收數據沒有數據來的話會阻塞等待
ret?=?recvfrom(serfdbufSIZE_BUFF0(void?*)&cli&len);
if(ret?<0)
{
perror(“recvfrom“);
exit(1);
}
//客戶端登陸請求
if(!strncmp(“IM_LOGIN:“buf9))
{
bool?user_name_ok_flag?=?true;
//判斷用戶名是否已經存在
pthread_mutex_lock(&mutex);
list_for_each_safe(posn&head->kernel_list)
{
//獲取當前正在遍歷的節點
p_max_struct=list_entry(posstruct?udp_clientkernel_list);
if(!(strncmp(p_max_struct->namebuf+9ret-9-1)))
{
//用戶名重復
ret?=?sprintf(buf“登陸失敗:%s\n““用戶名重復“);
ret?=?sendto(serfdbufret0(const?struct?sockaddr?*)&clilen);
user_name_ok_flag?=?false;
break;
}
}
pthread_mutex_unlock(&mutex);
if(user_name_ok_flag)
{
//申請一個節點存儲請求連接的客戶端的信息
struct?udp_client?*p?=?(struct?udp_client*)malloc(sizeof(struct?udp_client));

if(NULL?==?p)
{
perror(“malloc“);
exit(1);
}

memset(p0sizeof(struct?udp_client));
//保存客戶端的信息到鏈表中
p->cli?=?cli;
p->target_node?=?NULL;
p->time_

評論

共有 條評論