2013年(5)
分类: LINUX
2013-03-01 13:45:15
read()函数,顾名思义,read即为读,从文件中读出。
write函数,顾名思义,write即为写,写入到一个文件中。
在操作系统中,设备都被称之为文件,i/o设备也可以成为i/o文件操作
在sock编程中用read和write进行通信操作是很常见的
以下一个小编程供大家参考
client.c
#include
#include
#include
#include
#include
#include
#include
#include
int main(void)
{
struct sockaddr_in client_add;
int client=socket(AF_INET,SOCK_STREAM,0);
client_add.sin_family=AF_INET;
client_add.sin_port=htons(8143);
client_add.sin_addr.s_addr=inet_addr("127.0.0.1");
connect(client,(struct sockaddr*)&client_add,sizeof(struct sockaddr));
char buf[BUFSIZ];
while(strcmp(buf,"exit")!=0)
{
memset(buf,0,BUFSIZ);
fgets(buf);
write(client,buf,strlen(buf)+1);\多加一个'\0'
if(strcmp(buf,"exit")==0)
{
break;
}
memset(buf,0,BUFSIZ);
read(client,buf,64);
if(strcmp(buf,"exit")==0)
{
break;
}
puts(buf);
}
close(client);//关闭客户端
return 0;
}
server.c
#include
#include
#include
#include
#include
#include
#include
#include
int main()
{
struct sockaddr_in server_add;
int server_id=socket(AF_INET,SOCK_STREAM,0);
server_add.sin_family=AF_INET;
server_add.sin_port=htons(8143);
server_add.sin_addr.s_addr=inet_addr("127.0.0.1");
bind(server_id,(struct sockaddr*)&server_add,sizeof(struct sockaddr));
listen(server_id,2);
int client_id=accept(server_id,NULL,NULL);
char buf[BUFSIZ];
while(strcmp(buf,"exit")!=0)
{
read(client_id,buf,64);
if(strcmp(buf,"exit")==0)
{
break;
}
puts(buf);
memset(buf,0,BUFSIZ);
fgets(buf);
write(client_id,buf,strlen(buf)+1);
if(strcmp(buf,"exit\n")==0)
{
break;
}
}
close(client_id);
close(server_id);
return 0;
}