//---------------------------------------头文件区
#include "stdio.h"
#include "stdlib.h"
#include "string.h"
#include "unistd.h"
#include "sys/socket.h"
#include "sys/types.h"
#include "netinet/in.h"
#include "arpa/inet.h"
//---------------------------------------红定义
//---------------------------------------变量声明区
struct mesbuff{
int cfd;
char buff[256];
char ip[32];
};
int N=0;
int value=0;
int value1=0;
int cfdlist[10]={0};
int cfd;
int sendid=0;
struct mesbuff mes={0};
struct sockaddr_in caddr;
pthread_t sendrun,recvrun;
//---------------------------------------函数申明区
int MyConnect();
int MyClose();
void SendRun();
void RecvRun();
//---------------------------------------函数实现区
int MyConnect(){
cfd=socket(AF_INET,SOCK_STREAM,0);
if(cfd==-1){printf("创建sfd失败\n");return 0;}
caddr.sin_family=AF_INET;
caddr.sin_addr.s_addr=inet_addr("127.0.0.1");
caddr.sin_port=htons(11111);
value=connect(cfd,(struct sockaddr*)&caddr,sizeof caddr);
if(value==-1){printf("连接服务器失败\n");return 0;}
printf("连接服务器成功\n");
pthread_create(&sendrun,NULL,(void*)SendRun,NULL);
pthread_create(&recvrun,NULL,(void*)RecvRun,NULL);
return 1;
}
int MyClose(){
close(cfd);
exit(0);
return 1;
}
void SendRun(){
//printf("发送进程成功\n");
struct mesbuff temp;
while(1){
//printf("清输入:\n");
scanf("%s",temp.buff);
temp.cfd=sendid;
//printf("%d\n",temp.cfd);
sprintf(mes.ip,"%s",inet_ntoa(caddr.sin_addr));
value1=write(cfd,&temp,sizeof temp);
//if(value1>0)printf("发送成功\n");
}
}
void RecvRun(){
//printf("接收进程成功\n");
struct mesbuff temp;
while(1){
value=read(cfd,&temp,sizeof temp);
if(value>0){
if(temp.ip[0]-'0'==1)printf("接受到:%s\n",temp.ip);
printf("接受到:%d,%s\n",temp.cfd,temp.buff);
}
else {printf("服务器断开连接\n");MyClose();}
}
}
void ting(int n){
if(n==2){
printf("亲选择某人:");
scanf("%d",&sendid);
}
else{
MyClose();
exit(0);
}
}
//---------------------------------------主函数
int main(){
signal(2,ting);
signal(3,ting);
MyConnect();
pthread_join(sendrun);
pthread_join(recvrun);
//MyClose();
while(1);
return 0;
}
代码下载http://download.youkuaiyun.com/detail/hes_c/9851912