1、服务端代码recv.c
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
//服务器端代码
//实现服务器与客户端双向通信
int sock_ret = -1;
int acc_fd = -1;
void *send_sock(void *arg)
{
char *buf_s = malloc(100);
while(1)
{
memset(buf_s,0,100);
fgets(buf_s,100,stdin);
send(acc_fd,buf_s,100,0);
if(strcmp(buf_s,"ok\n")==0)
{
break;
}
}
}
int main(int argc, const char *argv[])
{
//创建套接字
sock_ret = socket(AF_INET,SOCK_STREAM,0);
if(-1==sock_ret)
{
perror("creat sock fail");
return -1;
}
//绑定网络地址
struct sockaddr_in serve,cilent_addr;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
int ret = bind(sock_ret,(struct sockaddr*)&serve,sizeof(serve));
if(-1==ret)
{
perror("bind fail");
}
//监听
int listen_ret = listen(sock_ret,4);
socklen_t cilent_len = sizeof(cilent_addr);
//等待连接
printf("等待连接\n");
acc_fd = accept(sock_ret,(struct sockaddr*)&cilent_addr,&cilent_len);
printf("连接成功\n");
//创建线程 发消息
pthread_t tid;
pthread_create(&tid,NULL,send_sock,NULL);
//接收消息
char *buf_r = malloc(100);
while(1)
{
memset(buf_r,0,100);
int recv_ret = recv(acc_fd,buf_r,100,0);
if(-1==recv_ret)
{
perror("recv sock fail");
}
printf("客户端:%s\n",buf_r);
if(strcmp(buf_r,"ok\n")==0)
{
break;
}
}
return 0;
}
2、客户端代码send.c
#include <stdio.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <pthread.h>
//实现服务器与客户端双向通信
int sock_ret = -1;
void *recv_sock(void *arg)
{
char *buf_r = malloc(100);
while(1)
{
memset(buf_r,0,100);
int recv_ret = recv(sock_ret,buf_r,100,0);
if(-1==recv_ret)
{
perror("recv sock fail");
}
printf("服务器:%s\n",buf_r);
if(strcmp(buf_r,"ok\n")==0)
{
break;
}
}
}
int main(int argc, const char *argv[])
{
//创建套接字
sock_ret = socket(AF_INET,SOCK_STREAM,0);
if(-1==sock_ret)
{
perror("creat sock fail");
return -1;
}
//绑定网络地址
struct sockaddr_in serve;
serve.sin_family = AF_INET;
serve.sin_port = htons(atoi(argv[2]));
serve.sin_addr.s_addr = inet_addr(argv[1]);
int ret = bind(sock_ret,(struct sockaddr*)&serve,sizeof(serve));
if(-1==ret)
{
perror("bind fail");
}
//发起连接
int con_ret = connect(sock_ret,(struct sockaddr*)&serve,sizeof(serve));
if(-1==con_ret)
{
perror("connect sock fail");
}
printf("连接成功\n");
//创建线程接消息
pthread_t tid;
pthread_create(&tid,NULL,recv_sock,NULL);
//发送消息
char *buf_s = malloc(100);
while(1)
{
memset(buf_s,0,100);
fgets(buf_s,100,stdin);
send(sock_ret,buf_s,100,0);
if(strcmp(buf_s,"ok\n")==0)
{
break;
}
}
return 0;
}