1.需求
①客户从标准输入读入一行文字,并写给了服务器 ②服务器从网络输入中读取了这个文本,并回射给客户 ③客户从网络输入中读取这个回射文本,并显示在标准输出上
2.server端代码
void dosth(int fd)
{
char szBuf[1024];
while(read(fd, szBuf, 1024) > 0)
{
write(fd, szBuf, sizeof(szBuf));
}
}
int main()
{
int sd, connsd;
pid_t pid;
struct sockaddr_in laddr, raddr;
int size;
char szBuf[1024];
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd < 0)
{
perror("socket");
exit(1);
}
laddr.sin_family = AF_INET;
laddr.sin_port = htons(1999);
inet_pton(AF_INET, "0.0.0.0", &laddr.sin_addr);
if(bind(sd, (void *)&laddr, sizeof(laddr)) < 0)
{
perror("bind");
exit(1);
}
listen(sd, 100);
size = sizeof(raddr);
while(1)
{
connsd = accept(sd, (void*)&raddr, &size);
inet_ntop(AF_INET, &raddr.sin_addr, szBuf, 1024);
pid = fork();
if(pid < 0)
{
perror("fork");
exit(1);
}
if(0 == pid)
{
fprintf(stdout, "[%s]:[%d] \n",
szBuf, ntohs(raddr.sin_port));
close(sd);
dosth(connsd);
close(connsd);
exit(0);
}
close(connsd);
}
exit(0);
}
3.客户端代码
int main(int argc, char *argv[])
{
int sd;
struct sockaddr_in raddr;
char buf[1024];
char rcvbuf[1024];
if(argc < 2)
{
fprintf(stderr, "Usage....\n");
exit(1);
}
sd = socket(AF_INET, SOCK_STREAM, 0);
if(sd < 0)
{
perror("socket");
exit(1);
}
raddr.sin_family = AF_INET;
raddr.sin_port = htons(1999);
inet_pton(AF_INET, argv[1], &raddr.sin_addr);
if(connect(sd, (void*)&raddr, sizeof(raddr)) < 0)
{
perror("connect");
exit(1);
}
while(NULL != fgets(buf, 1024, stdin))
{
write(sd, buf, sizeof(buf));
read(sd, rcvbuf, 1024);
puts(rcvbuf);
}
exit(0);
}
|