shutdown(socket sock,int flag);
shutdown的两个参数:sock是需要断开连接的socket文件操作符,flag可选三个数值:
SHUT_RD - 断开输入流下面的例子,利用socket创建了一个简单的文件传输服务器和客户端。服务器不断读取一个名叫file_server.c(就是服务端的代码所在文件)的文件,发给客户端,待读取完成后,接受客户端发过来的信息。服务端代码如下:
file_server.c:
#include
#include
#include
#include
#include
#define BUF_SIZE 30
void error_handling(char *message);
int main(int argc,char * argv[])
{
int serv_sd,clnt_sd;
FILE* fp;
char buf[BUF_SIZE];
int read_cnt;
struct sockaddr_in serv_adr,clnt_adr;
socklen_t clnt_adr_sz;
if(argc!=2)
{
printf("Usage %s ",argv[0]);
exit(1);
}
fp=fopen("file_server.c","rb");
serv_sd=socket(AF_INET,SOCK_STREAM,0);
memset(&serv_adr,0,sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_adr.sin_port=htons(atoi(argv[1]));
bind(serv_sd,(struct sockaddr*)&serv_adr,sizeof(serv_adr));
listen(serv_sd,5);
clnt_adr_sz=sizeof(clnt_adr);
clnt_sd=accept(serv_sd,(struct sockaddr*)&clnt_adr,&clnt_adr_sz);
while(1)
{
read_cnt=fread((void*)buf,1,BUF_SIZE,fp);
if(read_cnt
file_clent.c:
#include
#include
#include
#include
#include
#include
#define BUF_SIZE 30
void error_handling(char *message);
int main(int argc,char * argv[])
{
int serv_sock;
FILE* fp;
int read_cnt;
char buf[BUF_SIZE];
struct sockaddr_in serv_adr;
if(argc!=3)
{
printf("Usage %s ",argv[0]);
exit(1);
}
fp=fopen("recieve.dat","wb");
serv_sock=socket(AF_INET,SOCK_STREAM,0);
memset(&serv_adr,0,sizeof(serv_adr));
serv_adr.sin_family=AF_INET;
serv_adr.sin_addr.s_addr=inet_addr(argv[1]);
serv_adr.sin_port=htons(atoi(argv[2]));
connect(serv_sock,(struct sockaddr*)&serv_adr,sizeof(serv_adr));
while((read_cnt=read(serv_sock,buf,BUF_SIZE))!=0)
{
fwrite((void*)buf,1,read_cnt,fp);
printf("read_cnt= %d\n",read_cnt);
}
puts("recieved all data");
write(serv_sock,"Thank you",10);
fclose(fp);
close(serv_sock);
}
void error_handling(char *message)
{
fputs(message,stderr);
fputc('\n',stderr);
exit(1);
}
[Hyman@Hyman-PC csdn]$ ./serv 9190
message from client: Thank you
Github位置:
https://github.com/HymanLiuTS/NetDevelopment
克隆本项目:
git clone [email protected]:HymanLiuTS/NetDevelopment.git
获取本文源代码:
git checkout NL07