服务器端代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <sys/socket.h>
//服务器端
void main(int * argc, const char* argv[])
{
//创建监听套接字
int lfd = socket(AF_INET,SOCK_STREAM,0);
//绑定监听套接字
struct sockaddr_in serv;
memset(&serv,0,sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_addr.s_addr = htonl(INADDR_ANY);
serv.sin_port = htons(6868);
bind(lfd,(struct sockaddr*)&serv, sizeof(serv));
//设置监听
listen(lfd, 36);
//等待并接收链接请求
struct sockaddr_in client;
socklen_t client_len = sizeof(client);
char buf[1024] = {0};
while (1)
{
printf(“server is ready listen\n”);
int cfd = accept(lfd,(struct sockaddr *)&client, &client_len);
if(cfd == -1) {
perror("accept error");
exit(1);
}
//读数据
while (1) {
int len = read(cfd,&buf,sizeof(buf));
if(-1 == len)
{
perror("read error\n");
exit(1);
}
else if(0 == len)
{
printf("client close connect\n");
break;
}
else{
printf("client send data:%s\n",buf);
//发送数据
write(cfd,&buf,strlen(buf));
}
memset(buf,0,strlen(buf));
}
}
//关闭套接字
close(lfd);
}
客户端代码:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <arpa/inet.h>
#include <sys/un.h>
#include <sys/socket.h>
int main(int * argc, const char * argv[])
{
//初始化通信套接字
int cfd = socket(AF_INET,SOCK_STREAM,0);
//初始化服务器地址信息
struct sockaddr_in serv;
memset(&serv,0,sizeof(serv));
serv.sin_family = AF_INET;
serv.sin_port = htons(6868);
inet_pton(AF_INET,“INADDR_ANY”,&serv.sin_addr.s_addr);
//链接服务器
connect(cfd,(const struct sockaddr *)&serv,sizeof(serv));
while (cfd != -1)
{
//发送数据
char buf[1024];
printf("please input data\n");
fgets(buf,sizeof(buf),stdin);
write(cfd,&buf,strlen(buf));
//接收数据
int len = read(cfd,buf,sizeof(buf));
if(-1 == len)
{
perror("read error\n");
exit(1);
}
else if(0 == len)
{
printf("server close connect\n");
break;
}
else{
printf("recv data: %s\n", buf);
}
}
//关闭套接字
close(cfd);
}