#include <myhead.h>
#define PORT 8888
#define IP "192.168.125.60"
int main(int argc, const char *argv[])
{
//创建流式套接字 socket
int cfd=socket(AF_INET,SOCK_STREAM,0);
if(cfd<0){
ERR_MSG("socket");
return -1;
}
printf("套接字创建成功 cfd=%d\n",cfd);
//填充服务器地址信息结构体给connect函数连接
//真实的地址信息结构体根据地址族指定 AF_INET:man 7 ip
struct sockaddr_in sin;
sin.sin_family = AF_INET; //必须填AF_INET
sin.sin_port = htons(PORT); //服务器绑定的端口号
sin.sin_addr.s_addr = inet_addr(IP); //本机ip
//连接到服务器
if(connect(cfd,(struct sockaddr*)&sin,sizeof(sin))<0)
{
ERR_MSG("connect");
return -1;
}
printf("连接成功\n");
fd_set readfds, tempfds;
FD_ZERO(&readfds);
FD_SET(0, &readfds);
FD_SET(cfd, &readfds);
int res = -1;
int r_res = -1;
char buf[128] = "";
while(1){
tempfds = readfds;
res = select(cfd+1, &tempfds, NULL, NULL, NULL);
if(res < 0) {
ERR_MSG("select");
return -1;
} else if (res == 0) {
printf("超时\n");
continue;
}
if(FD_ISSET(0, &tempfds)){
printf("键盘事件\n");
bzero(buf, sizeof(buf));
fgets(buf, sizeof(buf), stdin);
buf[strlen(buf)-1] = 0;
if (send(cfd, buf, strlen(buf), 0) < 0) {
ERR_MSG("send");
continue;
}
}
if(FD_ISSET(cfd, &tempfds)){
printf("服务器已连接\n");
bzero(buf, sizeof(buf));
r_res = recv(cfd, buf, sizeof(buf), 0);
if(r_res < 0){
ERR_MSG("recv");
return -1;
}else if (r_res == 0) {
printf("已断开连接\n");
return -1;
}else {
printf("%s \n", buf);
}
}
}
//关闭
close(cfd);
return 0;
}
网络编程Day5
最新推荐文章于 2024-08-23 08:57:21 发布