目录
前言
三种模式简介:
1.多线程服务器
代码演示:
1.1server端
#include <pthread.h>
#include "net.h"
void cli_data_handle (void *arg);
int main (void)
{
int fd = -1;
struct sockaddr_in sin;
/* 1. 创建socket fd */
if ((fd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
perror ("socket");
exit (1);
}
/*优化4: 允许绑定地址快速重用 */
int b_reuse = 1;
setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &b_reuse, sizeof (int));
/*2. 绑定 */
/*2.1 填充struct sockaddr_in结构体变量 */
bzero (&sin, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_port = htons (SERV_PORT); //网络字节序的端口号
/*优化1: 让服务器程序能绑定在任意的IP上 */
#if 1
sin.sin_addr.s_addr = htonl (INADDR_ANY);
#else
if (inet_pton (AF_INET, SERV_IP_ADDR, (void *) &sin.sin_addr) != 1) {
perror ("inet_pton");
exit (1);
}
#endif
/*2.2 绑定 */
if (bind (fd, (struct sockaddr *) &sin, sizeof (sin)) < 0) {
perror ("bind");
exit (1);
}
/*3. 调用listen()把主动套接字变成被动套接字 */
if (listen (fd, BACKLOG) < 0) {
perror ("listen");
exit (1);
}
printf ("Server starting....OK!\n");
int newfd = -1;
/*4. 阻塞等待客户端连接请求 */
/* 优化: 用多进程/多线程处理已经建立号连接的客户端数据 */
pthread_t tid;
struct sockaddr_in cin;
socklen_t addrlen = sizeof (cin);
while (1) {
if ((newfd = accept (fd, (struct sockaddr *) &cin, &addrlen)) < 0) {
perror ("accept");
exit (1);
}
char ipv4_addr[16];
if (!inet_ntop (AF_INET, (void *) &cin.sin_addr, ipv4_addr, sizeof (cin))) {
perror ("inet_ntop");
exit (1);
}
printf ("Clinet(%s:%d) is connected!\n", ipv4_addr, ntohs (cin.sin_port));
/*
注意:下面tid重复使用并不规范。
假如有多个客户端连接,我们将丢失前面创建的线程标识符,导致无法释放线程等问题。
解决方法也很多,可以用数组,也可以设置变量判断线程是否执行完毕。
*/
pthread_create (&tid, NULL, (void *) cli_data_handle, (void *) &newfd);
}
close (fd);
return 0;
}
void cli_data_handle (void *arg)
{
int newfd = *(int *) arg;
printf ("handler thread: newfd =%d\n", newfd);
//..和newfd进行数据读写
int ret = -1;
char buf[BUFSIZ];
while (1) {
bzero (buf, BUFSIZ);
do {
ret = read (newfd, buf, BUFSIZ - 1);
} while (ret < 0 && EINTR == errno);
if (ret < 0) {
perror ("read");
exit (1);
}
if (!ret) { //对方已经关闭
break;
}
printf ("Receive data: %s\n", buf);
if (!strncasecmp (buf, QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
printf ("Client(fd=%d) is exiting!\n", newfd);
break;
}
}
close (newfd);
}
1.2 client端
-这里基本不变动,只是将服务器的ip和端口改为手动输入
/*./client serv_ip serv_port */
#include "net.h"
void usage (char *s)
{
printf ("\n%s serv_ip serv_port", s);
printf ("\n\t serv_ip: server ip address");
printf ("\n\t serv_port: server port(>5000)\n\n");
}
int main (int argc, char **argv)
{
int fd = -1;
int port = -1;
struct sockaddr_in sin;
if (argc != 3) {
usage (argv[0]);
exit (1);
}
/* 1. 创建socket fd */
if ((fd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
perror ("socket");
exit (1);
}
port = atoi (argv[2]);
if (port < 5000) {
usage (argv[0]);
exit (1);
}
/*2.连接服务器 */
/*2.1 填充struct sockaddr_in结构体变量 */
bzero (&sin, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_port = htons (port); //网络字节序的端口号
#if 0
sin.sin_addr.s_addr = inet_addr (SERV_IP_ADDR);
#else
if (inet_pton (AF_INET, argv[1], (void *) &sin.sin_addr) != 1) {
perror ("inet_pton");
exit (1);
}
#endif
if (connect (fd, (struct sockaddr *) &sin, sizeof (sin)) < 0) {
perror ("connect");
exit (1);
}
printf ("Client staring...OK!\n");
/*3. 读写数据 */
char buf[BUFSIZ];
int ret = -1;
while (1) {
bzero (buf, BUFSIZ);
if (fgets (buf, BUFSIZ - 1, stdin) == NULL) {
continue;
}
do {
ret = write (fd, buf, strlen (buf));
} while (ret < 0 && EINTR == errno);
if (!strncasecmp (buf, QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
printf ("Client is exiting!\n");
break;
}
}
/*4.关闭套接字 */
close (fd);
}
1.3头文件
#ifndef __MAKEU_NET_H__
#define __MAKEU_NET_H__
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <stdlib.h>
#include <strings.h>
#include <sys/types.h> /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h> /* superset of previous */
#define SERV_PORT 5001
#define SERV_IP_ADDR "192.168.2.116"
#define BACKLOG 5
#define QUIT_STR "quit"
#endif
2.多进程服务器
2.1servet端
#include <pthread.h>
#include <signal.h>
#include "net.h"
void cli_data_handle (void *arg);
void sig_child_handle(int signo)
{
if(SIGCHLD == signo) {
waitpid(-1, NULL, WNOHANG);
}
}
int main (void)
{
int fd = -1;
struct sockaddr_in sin;
signal(SIGCHLD, sig_child_handle);
/* 1. 创建socket fd */
if ((fd = socket (AF_INET, SOCK_STREAM, 0)) < 0) {
perror ("socket");
exit (1);
}
/*优化4: 允许绑定地址快速重用 */
int b_reuse = 1;
setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, &b_reuse, sizeof (int));
/*2. 绑定 */
/*2.1 填充struct sockaddr_in结构体变量 */
bzero (&sin, sizeof (sin));
sin.sin_family = AF_INET;
sin.sin_port = htons (SERV_PORT); //网络字节序的端口号
/*优化1: 让服务器程序能绑定在任意的IP上 */
#if 1
sin.sin_addr.s_addr = htonl (INADDR_ANY);
#else
if (inet_pton (AF_INET, SERV_IP_ADDR, (void *) &sin.sin_addr) != 1) {
perror ("inet_pton");
exit (1);
}
#endif
/*2.2 绑定 */
if (bind (fd, (struct sockaddr *) &sin, sizeof (sin)) < 0) {
perror ("bind");
exit (1);
}
/*3. 调用listen()把主动套接字变成被动套接字 */
if (listen (fd, BACKLOG) < 0) {
perror ("listen");
exit (1);
}
printf ("Server starting....OK!\n");
int newfd = -1;
/*4. 阻塞等待客户端连接请求 */
struct sockaddr_in cin;
socklen_t addrlen = sizeof (cin);
while(1) {
pid_t pid = -1;
if ((newfd = accept (fd, (struct sockaddr *) &cin, &addrlen)) < 0) {
perror ("accept");
break;
}
/*创建一个子进程用于处理已建立连接的客户的交互数据*/
if((pid = fork()) < 0) {
perror("fork");
break;
}
if(0 == pid) { //子进程中
close(fd);
char ipv4_addr[16];
if (!inet_ntop (AF_INET, (void *) &cin.sin_addr, ipv4_addr, sizeof (cin))) {
perror ("inet_ntop");
exit (1);
}
printf ("Clinet(%s:%d) is connected!\n", ipv4_addr, ntohs(cin.sin_port));
cli_data_handle(&newfd);
return 0;
} else { //实际上此处 pid >0, 父进程中
close(newfd);
}
}
close (fd);
return 0;
}
void cli_data_handle (void *arg)
{
int newfd = *(int *) arg;
printf ("Child handling process: newfd =%d\n", newfd);
//..和newfd进行数据读写
int ret = -1;
char buf[BUFSIZ];
while (1) {
bzero (buf, BUFSIZ);
do {
ret = read (newfd, buf, BUFSIZ - 1);
} while (ret < 0 && EINTR == errno);
if (ret < 0) {
perror ("read");
exit (1);
}
if (!ret) { //对方已经关闭
break;
}
printf ("Receive data: %s\n", buf);
if (!strncasecmp (buf, QUIT_STR, strlen (QUIT_STR))) { //用户输入了quit字符
printf ("Client(fd=%d) is exiting!\n", newfd);
break;
}
}
//在unix和linux平台需要考虑多进程的情况,fork时,子进程继承父进程所拥有的文件描述符,需要所有拥有者都close文件描述符才会把资源销毁,所以需要使用引用计数。
close (newfd);
}
其余:客户端不变,头文件添加 #include<signal.h>
注意: 子进程的回收和退出
3. TCP编程的函数API(补充send和recv)
网络发送数据:send()/write()
send()比write多一个参数flags:
flags:
一般填写0,此时和write()作用一样
特殊的标志:
MSG_DONTWAIT: Enables nonblocking operation; 非阻塞版本
MSG_OOB:用于发送TCP类型的带外数据(out-of-band)
网络中接受收据: recv()/read()
flags:
一般填写0,此时和read()作用一样
特殊的标志:
MSG_DONTWAIT: Enables nonblocking operation; 非阻塞版本
MSG_OOB:用于发送TCP类型的带外数据(out-of-band)
MSG_PEEK:
This flag causes the receive operation to return data from
the beginning of the receive queue without removing that
data from the queue. Thus, a subsequent receive call will
return the same data.
注意: 关于close文件描述符
在unix和linux平台需要考虑多进程的情况,fork时,子进程继承父进程所拥有的文件描述符,需要所有拥有者都close文件描述符才会把资源销毁,所以需要使用引用计数。
参考文献:
clinux 文件描述符 引用计数(close(fd)只是使fd的引用计数-1)
总结
线程创建时,pthread_t *thread
是一个指向 pthread_t
类型变量的指针,用于存储新创建线程的标识符。每次调用 pthread_create
时,你都应该传递一个不同的 pthread_t
变量的地址,或者确保在每次调用之前重新初始化或更新该变量。
如果你重复使用了同一个 pthread_t
变量而没有重新初始化或更新它,那么新的线程标识符会覆盖旧的线程标识符。这本身不会导致运行时错误,但你会失去对之前创建线程的引用,这可能会导致一些问题:
-
无法等待线程结束:如果你想要等待之前创建的线程结束(使用
pthread_join
),你将无法做到,因为你已经丢失了那个线程的标识符。 -
资源管理问题:如果线程需要释放资源(如内存、文件描述符等),并且你依赖于主线程来等待它们完成,那么由于丢失了线程标识符,这些资源可能不会被正确释放,导致资源泄漏。
-
调试和跟踪困难:在调试和跟踪程序时,如果你无法引用特定的线程,那么确定哪个线程执行了哪些操作会变得非常困难。
因此,虽然从技术上讲重复使用 pthread_t
变量本身不会导致运行时错误,但这样做通常是不好的做法,因为它会导致资源管理问题和调试困难。每次调用 pthread_create
时,都应该使用一个新的或已经重置的 pthread_t
变量来存储线程标识符。