#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
//*********************************announce*****************
//********************************params*******************
int main(int argc, char* argv[])
{
struct timeval timeout={0,0};
int server_sockfd,maxfdp;
struct sockaddr_in server_addr, client_addr;
char recv_buf[100];
int nbytes = 0;
socklen_t len = 0;
fd_set fds;
// create socket
server_sockfd = socket(AF_INET, SOCK_DGRAM, 0);
if (server_sockfd < 0)
{
printf("error create\n");
return -1;
}
printf("create success\n");
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);//get any ip
server_addr.sin_port = htons(atoi(argv[1]));//set port
bind(server_sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr));
printf("bind success\n");
len = sizeof(client_addr);
while(1)
{
printf("check\n");
FD_ZERO(&fds); //每次循环都要清空集合,否则不能检测描述符变化
FD_SET(server_sockfd,&fds); //添加描述符
maxfdp=server_sockfd+1; //描述符最大值加1
int res=select(maxfdp,&fds,&fds,NULL,&timeout);
printf("%d\n",res);
switch(res) //select使用
{
case -1: exit(-1);break; //select错误,退出程序
case 0:
printf("timeout\n");
break; //再次轮询
default:
if(FD_ISSET(0,&fds)){
fgets(recv_buf, 100, stdin);
sendto(server_sockfd,recv_buf,strlen(recv_buf),0,(struct sockaddr *)&client_addr,len);
}
if(FD_ISSET(server_sockfd,&fds)){
nbytes=recvfrom(server_sockfd, recv_buf, 100, 0, (struct sockaddr *)&client_addr, &len);//接受网络数据
printf("recv %d bytes:%s.\n", nbytes, recv_buf);
}// end if break;
}// end switch
}//end while
return 0;
}
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char* argv[])
{
int sock_fd;
struct sockaddr_in server_addr;
char recv_buf[100];
int nbytes = 0;
socklen_t len = 0;
/* 创建Socket */
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (sock_fd < 0)
{
printf("客户端Socket创建失败");
return -1;
}
/* 绑定ip和端口 */
bzero(&server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = inet_addr(argv[1]);
server_addr.sin_port = htons(atoi(argv[2]));//指定端口号
while(1)
{
len = sizeof(server_addr);
//接收用户输入,发送给服务端
printf("请输入要发送给服务端的数据:");
fgets(recv_buf, 100, stdin);
sendto(sock_fd,recv_buf,100,0,(struct sockaddr *)(&server_addr),len);
/* 接收UDP客户端的数据 */
/*
len = sizeof(server_addr);
nbytes = recvfrom(sock_fd, recv_buf, 100, 0, (struct sockaddr *)&server_addr, &len);
recv_buf[nbytes] = '\0';
printf("recv %d bytes:%s.\n", nbytes, recv_buf);
*/
}
return 0;
}