本程序实现客户端向服务器发送一个字符串,服务器将接收到的字符串回送给客户端。
// unp.h
#ifndef _UNP_H
#define _UNP_H
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <assert.h>
#define MAXLINE 4096
#define ERR_EXIT(m) \
do{ \
perror(m); \
exit(EXIT_FAILURE); \
}while(0)
#endif
下面是客户端代码:
#include "unp.h"
int main()
{
int sockfd;
char sendbuff[MAXLINE];
struct sockaddr_in servaddr;
ssize_t n;
if( (sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
ERR_EXIT("socket err");
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6666);
servaddr.sin_addr.s_addr = inet_addr("127.0.0.1");
if(connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
ERR_EXIT("connect err");
for(; ;){
fgets(sendbuff, MAXLINE, stdin);
if( (n = write(sockfd, sendbuff, strlen(sendbuff))) < 0)
ERR_EXIT("write err");
memset(sendbuff, 0 ,sizeof(sendbuff));
if( (n = read(sockfd, sendbuff, sizeof(sendbuff))) < 0)
ERR_EXIT("read err");
fputs(sendbuff, stdout);
memset(sendbuff, 0, sizeof(sendbuff));
}
close(sockfd);
}
下面是服务端代码:
#include "unp.h"
int main()
{
int listenfd, connfd;
struct sockaddr_in servaddr;
char recvbuff[MAXLINE];
ssize_t n;
if( (listenfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0)
ERR_EXIT("socket err");
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(6666);
servaddr.sin_addr.s_addr = INADDR_ANY;
if(bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0)
ERR_EXIT("bind err");
if(listen(listenfd, SOMAXCONN) < 0)
ERR_EXIT("listen err");
if( (connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) < 0)
ERR_EXIT("accept err");
for(; ;){
if( (n = read(connfd, recvbuff, sizeof(recvbuff))) < 0)
ERR_EXIT("read err");
recvbuff[n] = '\0';
fputs(recvbuff, stdout);
if( (n = write(connfd, recvbuff, strlen(recvbuff))) < 0)
ERR_EXIT("write err");
memset(recvbuff, 0, sizeof(recvbuff));
}
close(connfd);
close(listenfd);
return 0;
}