server
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
void server_send(void);
int client_fd;
int main(int argc, char const *argv[])
{
//1、创建套接字
int sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd == -1)
{
perror("socket");
exit(1);
}
printf("socket create success\n");
//2、绑定地址
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(8848);
addr.sin_addr.s_addr = inet_addr("192.168.124.72");
int ret = bind(sock_fd, (const struct sockaddr *)&addr, sizeof(addr));
if (ret == -1)
{
perror("bind");
exit(1);
}
//3、监听
printf("server started\n");
ret = listen(sock_fd, 4); //最大连接数为10
if (ret == -1)
{
perror("listen");
exit(1);
}
printf("server listening\n");
//4、等待连接
struct sockaddr_in client_addr;
socklen_t client_addr_len = sizeof(client_addr);
client_fd = accept(sock_fd, (struct sockaddr *)&client_addr, &client_addr_len);
if (client_fd < 0)
{
perror("accept");
exit(1);
}
printf("client connected\n");
//创建服务器发送线程
pthread_t tid;
pthread_create(&tid, NULL, (void *)server_send, NULL);
//5、通信
char buf[1024];
while (1)
{
memset(buf, 0, sizeof(buf));
ret = recv(client_fd, buf, sizeof(buf), 0);
if (ret == -1)
{
perror("read");
exit(1);
}
else if (ret == 0)
{
printf("client closed\n");
break;
}
printf("client say:%s\n", buf);
//send(client_fd, buf, strlen(buf), 0);
}
close(client_fd);
close(sock_fd);
return 0;
}
void server_send(void)
{
char buf[1024];
while (1)
{
memset(buf, 0, sizeof(buf));
printf("请输入要发送的内容:\n");
fgets(buf, sizeof(buf), stdin);
send(client_fd, buf, strlen(buf)-1, 0);
}
}
client
#include <unistd.h>
#include <string.h>
#include <pthread.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <stdlib.h>
int sock_fd;
void clent_recv(void);
int main(int argc, char const *argv[])
{
//1、创建套接字
sock_fd = socket(AF_INET, SOCK_STREAM, 0);
if (sock_fd == -1)
{
perror("socket");
exit(1);
}
printf("socket create success\n");
//2、连接服务器
struct sockaddr_in addr;
addr.sin_family=AF_INET;
addr.sin_port=htons(8848);
addr.sin_addr.s_addr=inet_addr("192.168.124.72");
int ret = connect(sock_fd,(const struct sockaddr *)&addr,sizeof(addr));
if(ret == -1)
{
perror("connect");
exit(1);
}
printf("connect success\n");
//3、创建客户端接受线程
pthread_t pid;
pthread_create(&pid,NULL,(void *)clent_recv,NULL);
//4、通信
char buf[1024];
while (1)
{
memset(buf,0,sizeof(buf));
printf("请输入要发送的内容:\n");
fgets(buf,sizeof(buf),stdin);
ret = send(sock_fd,buf,strlen(buf)-1,0);
if (ret == -1)
{
perror("send");
exit(1);
}
}
close(sock_fd);
return 0;
}
void clent_recv(void)
{
char buf[1024];
while(1)
{
memset(buf,0,sizeof(buf));
int ret = recv(sock_fd,buf,sizeof(buf),0);
if (ret == -1)
{
printf("read error\n");
perror("read");
exit(1);
}
else if (ret == 0)
{
printf("client closed\n");
break;
}
printf("server say:%s\n", buf);
}
}