/*******************************socket_test*******************************************/
server:
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAXLEN 5000
int main(int argc , char **argv)
{
unsigned char buffer[MAXLEN]={0};
int flag=0;
struct sockaddr_in my_socket;
struct sockaddr_in from_socket;
struct timeval timo;
fd_set readfds;
//memset(&my_socket,0,sizeof(my_socket));
//bzero()
my_socket.sin_family = AF_INET;
my_socket.sin_port = htons(8000);
my_socket.sin_addr.s_addr= INADDR_ANY;
int fd=socket(AF_INET,SOCK_DGRAM,0);
if(fd<0)
{
printf("the socket_fd error!\n");
return 1;
}
int size_len = sizeof(struct sockaddr_in);
int bind_flag=bind(fd,(struct sockaddr *)&my_socket,sizeof(struct sockaddr));
if(bind_flag ==-1)
{
printf("there is the bind error\n");
}
while(1)
{
FD_ZERO(&readfds);
FD_SET(fd,&readfds);
timo.tv_sec=5;
timo.tv_usec=0;
FILE *file;
char *path="./server.c";
switch(select(fd+1,&readfds,NULL,NULL,&timo))
{
case -1:
continue;
case 0:
continue;
}
if(FD_ISSET(fd,&readfds))
{
recvfrom(fd,buffer,MAXLEN,0,(struct sockaddr *)&from_socket,&size_len);
printf("%s\n",buffer);
file=fopen(path,"r+");
if(file==NULL)
{
printf("open fail");
}
else
{
fseek(file,0,SEEK_SET);
memset(buffer,0,MAXLEN);
fread(buffer,MAXLEN,1,file);
fclose(file);
}
sendto(fd,buffer,sizeof(buffer),0,(struct sockaddr*)&from_socket,sizeof(from_socket));
}
}
return 0;
}
#include <stdio.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#define MAXLEN 5000
int main(int argc,char **argv)
{
unsigned char buffer[MAXLEN]={0};
int sock_flag;
struct sockaddr_in svrsocket;
struct sockaddr_in fromsocket;
// memset(svrsocket,0,sizeof(svrsocket));
svrsocket.sin_family=AF_INET;
svrsocket.sin_addr.s_addr=inet_addr("127.0.0.1");
svrsocket.sin_port=htons(8000);
fromsocket.sin_family=AF_INET;
fromsocket.sin_addr.s_addr=INADDR_ANY;
fromsocket.sin_port=htons(9000);
int fd=socket(AF_INET,SOCK_DGRAM,0);
FILE *file;
char *name="client.c";
char path[100];
memset(path,0,100);
sprintf(path,"%s%s","./",name);
file = fopen(path,"r+");
if(file == NULL)
{
printf("open fail %s",path);
}
else
{
fseek(file,0,SEEK_SET);
fread(buffer,MAXLEN,1,file);
fclose(file);
}
sendto(fd,buffer,MAXLEN,0,(struct sockaddr *)&svrsocket,sizeof(svrsocket));
memset(buffer,0,MAXLEN);
int len = sizeof(struct sockaddr_in);
recvfrom(fd,buffer,MAXLEN,0,(struct sockaddr*)&fromsocket,&len);
printf("%s\n",buffer);
return 0;
}