client客戶端:
#include #include #include #include #include #include #include #include #include #include #include #define maxbuf 1024
int main()
/* 初始化伺服器端(對方)的位址和埠資訊 */
bzero(&dest, sizeof(dest));
dest.sin_family = af_inet;
dest.sin_port = htons(3333);
if (inet_aton("127.0.0.1", (struct in_addr *) &dest.sin_addr.s_addr) == 0)
/* 連線伺服器 */
if (connect(sockfd, (struct sockaddr *) &dest, sizeof(dest)) != 0)
printf
("\n準備就緒,可以開始聊天了……直接輸入訊息回車即可發資訊給對方\n");
while (1) else if (retval == 0) else
}if (fd_isset(0, &rfds))
/* 發訊息給伺服器 */
len = send(sockfd, buffer, strlen(buffer) - 1, 0);
if (len > 0) else}}
}/* 關閉連線 */
close(sockfd);
return 0;
}
server客戶端:
#include #include #include #include #include #include #include #include #include #include #include #include #include static void sigchld_handler()
/* */
signal(sigchld,sigchld_handler);
} #define maxbuf 1024
int main()
bzero(&my_addr, sizeof(my_addr));
my_addr.sin_family = af_inet;
my_addr.sin_port = htons(3333);
my_addr.sin_addr.s_addr = inaddr_any;
if (bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr))
== -1)
if (listen(sockfd, lisnum) == -1)
pid_t pid;
while (1) else
printf("server: got connection from %s, port %d, socket %d\n",
inet_ntoa(their_addr.sin_addr),
ntohs(their_addr.sin_port), new_fd);
printf("fork之前,accept之後\n");
pid=fork();
if(pid>0)
printf("in child\n");
close(sockfd);
/* 開始處理每個新連線上的資料收發 */
printf
("\n準備就緒,可以開始聊天了……直接輸入訊息回車即可發資訊給對方\n");
int count=0;
while (1) else if (retval == 0) else
len = send(new_fd, buf, strlen(buf) - 1, 0);
count++;
printf("send count= %d\n",count);
if (len > 0)
printf
("訊息:%s\t傳送成功,共傳送了%d個位元組!,套接字為:%d \n",
buf, len,new_fd);
else
}if (fd_isset(new_fd, &rfds))
}else
}count++;
printf("out count= %d\n",count);}}
close(new_fd);
/* 處理每個新連線上的資料收發結束 */
printf("還要和其它連線聊天嗎?(no->退出)");
fflush(stdout);
bzero(buf, maxbuf + 1);
fgets(buf, maxbuf, stdin);
if (!strncasecmp(buf, "no", 2))
}close(sockfd);
return 0;
}
Select模型學習
通過呼叫select函式可以確定乙個或多個套接字的狀態,判斷套接字上是否有資料,或 者能否向乙個套接字寫入資料。select模型是最常見的i o模型。使用int select int nfds fd set far readfds fd set far writefds,fd set far exc...
Select網路模型
mysockt.h pragma once define maxnum 64 include pragma comment lib,ws2 32.lib define um user wm user 1 向視窗發訊息 enum nettype class cmysocket mysocket.cpp...
Select 網路模型
maxfd 最大描述符加1 fd set操作集合 include include include include intselect int maxfdp,fd set readset,fd set writeset,fd set exceptset,struct timeval timeout m...