第一篇的UDP链接 服务端代码server_tcp.c:
在这里插入代码片#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#define LISTENQ 20
#define MAXLINE 100
void str_echo(int sockfd){
ssize_t n;
char buf[MAXLINE];
again:
while((n=read(sockfd,buf,MAXLINE))>0){
write(sockfd,buf,n);
}
if(n<0&&errno==EINTR)
goto again;
else if(n<0){
perror("fail to read\n");
exit(EXIT_FAILURE);
}
}
int main(int argc, char **argv){
int listenfd,connfd;
socklen_t clilen;
struct sockaddr_in cliaddr,servaddr;
listenfd=socket(AF_INET,SOCK_STREAM,0);
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_addr.s_addr=inet_addr("127.0.0.1");
servaddr.sin_port = htons(1234);
bind(listenfd,(struct sockaddr *) &servaddr,sizeof(servaddr));
listen(listenfd,LISTENQ);
for(;;){
clilen=sizeof(cliaddr);
connfd=accept(listenfd,(struct sockaddr *) &cliaddr, &clilen);
str_echo(connfd);
}
}
客户端代码client_tcp.c:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <errno.h>
#define LISTENQ 20
#define MAXLINE 100
void str_cli(FILE *fp, int sockfd)
{
char sendline[MAXLINE], recvline[MAXLINE];
while(fgets(sendline,MAXLINE,fp)!=NULL){
write(sockfd,sendline,strlen(sendline));
if(read(sockfd,recvline,MAXLINE)==0){
printf("server terminated prematurely");
exit(EXIT_FAILURE);
}
fputs(recvline,stdout);
}
}
int main(int argc, char **argv){
int sockfd;
struct sockaddr_in servaddr;
if(argc!=2){
printf("error input\n");
exit(EXIT_FAILURE);
}
sockfd=socket(AF_INET,SOCK_STREAM,0);
memset(&servaddr,0,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(1234);
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
connect(sockfd, (struct sockaddr *) &servaddr,sizeof(servaddr));
str_cli(stdin,sockfd);
}
再补个UDP的: 明天再来试试能不能把那个lab做了,今天就先总结了一下这两篇博客里的知识点
|