通过线程实现客户端与服务端的简易双人聊天
头文件
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <arpa/inet.h>
#include<string.h>
#include<pthread.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<errno.h>
#include<netdb.h>
1,客户端主函数代码
int main()
{
//监听套接字文件描述符
int listenFd = -1;
//连接套接字的文件描述符
int connFd = -1;
//服务器的地址结构
struct sockaddr_in servAddr = {0};
//客户端的地址结构
struct sockaddr_in cliAddr = {0};
socklen_t len = sizeof(cliAddr);
int ret;
char buf[100] = {0};
//创建套接字
listenFd = socket(PF_INET, SOCK_STREAM, 0);
if(listenFd < 0)
{
perror("socket error!\n");
return -1;
}
printf("socket ok!\n");
//绑定ip地址和端口号
servAddr.sin_family = PF_INET;
servAddr.sin_port = htons(10086);
servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = bind(listenFd, (struct sockaddr *)&servAddr, sizeof(servAddr));
if(ret < 0)
{
perror("bind error!");
close(listenFd);
return -1;
}
printf("bind ok!\n");
//创建监听队列(使得主动的套接字变成可以被连接的被动套接字)
ret = listen(listenFd, 1);
if(ret < 0)
{
perror("listen error");
close(listenFd);
return -1;
}
printf("listening....\n");
//等待并建立连接
connFd = accept(listenFd, (struct sockaddr *)&cliAddr, &len);
if(connFd < 0)
{
perror("accept error!");
close(listenFd);
return -1;
}
// printf("IP:%s,PORT:%d accept ok!\n", inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port));i
while(1)
{
pthread_t tid;
pthread_create(&tid,NULL,thread,&connFd);
}
return 0;
}
void *thread(void *vargp)
{
pthread_t tid1,tid2;
int connfd = *((int *)vargp);
int idata;
char temp[100];
pthread_create(&tid1,NULL,threadsend,vargp);
pthread_create(&tid2,NULL,threadrecv,vargp);
return NULL;
}
2,服务端主函数代码
int main()
{
int sockFd = -1;
//服务器的地址结构
struct sockaddr_in servAddr = {0};
int ret;
char buf[100] = {0};
//创建套接字
sockFd = socket(PF_INET, SOCK_STREAM, 0);
if(sockFd < 0)
{
perror("socket error!\n");
return -1;
}
printf("socket ok!\n");
//按照服务器的ip地址和端口号连接服务器
servAddr.sin_family = PF_INET;
servAddr.sin_port = htons(10086);
servAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
ret = connect(sockFd, (struct sockaddr *)&servAddr, sizeof(servAddr));
if(ret < 0)
{
perror("connect error!");
close(sockFd);
return -1;
}
printf("connect ok!\n");
pthread_t tid1,tid2;
printf("connected\n");
while(1){
pthread_create(&tid1,NULL,threadsend,&sockFd);
pthread_create(&tid2,NULL,threadrecv,&sockFd);
}
return 0;
}
3,接受发送信息函数
void *thread(void *vargp)
{
pthread_t tid1,tid2;
int connfd = *((int *)vargp);
int idata;
char temp[100];
pthread_create(&tid1,NULL,threadsend,vargp);
pthread_create(&tid2,NULL,threadrecv,vargp);
return NULL;
}
void *threadsend(void *vargp)
{
int connFd = *((int *)vargp);
int idata;
char temp[100];
while(1)
{
fgets(temp,sizeof(temp),stdin);
send(connFd,temp,sizeof(temp),0);
printf("send ok\r\n");
}
printf("server send\n");
return NULL;
}
void *threadrecv(void *vargp)
{
char temp[100];
int connFd = *((int *)vargp);
while(1)
{
int idata = 0;
idata = recv(connFd,temp,sizeof(temp),0);
if(idata > 0)
{
printf("recv :%s\r\n",temp);
}
}
return NULL;
}