1.多进程
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#include <signal.h>
#include <sys/wait.h>
#define PORT 8000
#define IP "192.168.126.140"
typedef void (*sighandler_t)(int);
int chat(int newfd);
#define PRINT_ERR(msg) \
do \
{ \
perror("msg"); \
return -1; \
} while (0)
void handler(int sig)
{
while(waitpid(-1,NULL,WNOHANG) > 0);
return;
}
int main(int argc, const char *argv[])
{
int sig;
signal(17,handler);
pid_t pid;
int sfd = socket(AF_INET, SOCK_STREAM, 0); // 创建 socket 套接字;
if (sfd == -1)
PRINT_ERR("socket");
struct sockaddr_in sin; // 地址结构体
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
if (0 > bind(sfd, (struct sockaddr *)&sin, sizeof(sin))) // 绑定自己 IP 和 端口
PRINT_ERR("bind");
if (listen(sfd, 100)) // 单次最多发送 100 个长度
PRINT_ERR("listen");
int newfd;
while (1)
{
newfd = accept(sfd, NULL, NULL); // 开启一块新的空间和其描述符
if (-1 == newfd)
PRINT_ERR("accept");
else
printf("链接已建立\n");
pid = fork();
if (pid < 0)
{
PRINT_ERR("fork");
}
else if (pid == 0)
{
close(sfd);
chat(newfd);
exit(0);
}
else if (pid > 0)
{
close(newfd);
}
}
close(sfd);
return 0;
}
int chat(int newfd)
{
while (1)
{
char buff[100] = {0}; // 接受和打印消息的变量
int res;
while (res = recv(newfd, &buff, sizeof(buff), 0))
{
if (-1 == res)
PRINT_ERR("recv");
// printf("res = %d\n",res);
printf("%s\n", buff);
send(newfd, buff, sizeof(buff), 0);
}
}
}
2.多线程
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <strings.h>
#include <string.h>
#include <pthread.h>
#define PORT 8000
#define IP "192.168.126.140"
void *chat(void *arg);
#define PRINT_ERR(msg) \
do \
{ \
perror("msg"); \
return -1; \
} while (0)
typedef struct cli_info
{
int newfd;
} cli_info;
int main(int argc, const char *argv[])
{
pthread_t tid;
int sfd = socket(AF_INET, SOCK_STREAM, 0); // 创建 socket 套接字;
if (sfd == -1)
PRINT_ERR("socket");
struct sockaddr_in sin; // 地址结构体
sin.sin_family = AF_INET;
sin.sin_port = htons(PORT);
sin.sin_addr.s_addr = inet_addr(IP);
if (0 > bind(sfd, (struct sockaddr *)&sin, sizeof(sin))) // 绑定自己 IP 和 端口
PRINT_ERR("bind");
if (listen(sfd, 100)) // 单次最多发送 100 个长度
PRINT_ERR("listen");
int newfd;
while (1)
{
newfd = accept(sfd, NULL, NULL); // 开启一块新的空间和其描述符
if (pthread_create(&tid, NULL, chat, &newfd) < 0)
PRINT_ERR("pthread_create");
}
close(sfd);
return 0;
}
void *chat(void *arg)
{
pthread_detach(pthread_self());
int newfd = *(int *)arg;
char buff[100] = {0}; // 接受和打印消息的变量
int res;
while (res = recv(newfd, &buff, sizeof(buff), 0))
{
if (-1 == res)
{
perror("子线程接受失败\n");
close(newfd);
pthread_exit(NULL);
}
// printf("res = %d\n",res);
printf("%s\n", buff);
send(newfd, buff, sizeof(buff), 0);
}
close(newfd);
pthread_exit(NULL);
}