偽代碼實(shí)現(xiàn): typedef struct info
int fd; struct sockaddr_in addr;
{
}Info;
int main()
int i = 0; int fds[200]; // 創(chuàng)建監(jiān)聽(tīng) 的套接字 int lfd = socket(); // 綁定 bind(lfd, struct sockaddr_in, len) // 監(jiān)聽(tīng) listen(lfd, num);
while(1) {
// 等待并接受連接請(qǐng)求 int fds[i] = accept(lfd, &struct sockaddr_in, &len);
// 創(chuàng)建子線(xiàn)程 pthread_create(&threadId, NULL, do_child, (void*)&fds[i]);
// 設(shè)置線(xiàn)程分離 pthread_deatch(threadid); i++;
}
}
void* do_child(void* arg)
{
int cfd = (int)arg; // 與客戶(hù)端通信
// 與客戶(hù)端通信
recv(cfd, buf, len, 0);
printf(連接過(guò)來(lái)客戶(hù)端信息)
send();
}
需要注意:全局變量: 共享1. 如何做數(shù)據(jù)傳輸2. 如果線(xiàn)程之間有數(shù)據(jù)交互 -線(xiàn)程同步 3. 文件描述符的個(gè)數(shù)