linux 多執行緒聊天伺服器

2021-07-12 02:52:11 字數 2248 閱讀 6527

自己寫的linux多執行緒聊天伺服器,可以實現併發,通過鍊錶新增人數。
#include #include #include #include #include #include #include #include #include #include #include typedef struct  client;

typedef struct _node node;

node* head = null;

void list_init()

void list_insert(client* ps)

void list_erase(int sockfd)

p = p->next; }}

void list_tracvel()

}int list_size()

return cnt;

}void send_all(char* msg)

}void * thread_handler(void * p) ;

recv(clientfd, name, sizeof(name), 0);

char *q = strstr(name, "\r\n");

if (q)

*q = "\0";

client c;

c.sockfd = clientfd;

strcpy(c.name, name);

char online_msg[128] = ; //傳送上資訊

sprintf(online_msg, "%s is online!\r\n", c.name);

send_all(online_msg);

list_insert(&c); //鍊錶新增

while (1) ;

int size = recv(clientfd, recv_msg, sizeof(recv_msg), 0);

if (size <= 2 || strncasecmp("quit", recv_msg, 4) == 0)

break;

send_all(recv_msg);

printf("a client %s:%d exit \n", inet_ntoa(c_addr.sin_addr),

ntohs(c_addr.sin_port));

char wel_msg[128] = "welcome back to lizhu's chat room!\r\n";

send(clientfd, wel_msg, strlen(wel_msg), 0);

list_erase(clientfd); //鍊錶新增

char offline_msg[128] = ; //傳送上資訊

sprintf(offline_msg, "%s is online!\r\n", c.name);

send_all(offline_msg);

close(clientfd);

return null; }}

void start()

int opt = 1; //1代表可以重用 解決伺服器端口占用

setsockopt(sockfd, sol_socket, so_reuseaddr, &opt, 4); //4代表opt的大小

struct sockaddr_in ser_addr;

ser_addr.sin_family = af_inet;

ser_addr.sin_addr.s_addr = inaddr_any; //inet_addr("127.0.0.1");

ser_addr.sin_port = htons(3000);

int ret = bind(sockfd, (struct sockaddr*) &ser_addr, 16);

if (-1 == ret)

ret = listen(sockfd, 20);

if (-1 == ret)

printf("lizhu server is ready\n");

while (1)

printf("a client connected\n");

pthread_t tid;

int ret = pthread_create(&tid, null, thread_handler, &newfd);

if (ret)

} close(sockfd);

}int main(int agc, char *agv)

Linux多執行緒伺服器 優化

例1 使用多執行緒提高響應速度假設我們有乙個類似計算器的服務,輸入數字公式,返回相應的結果,如果無解,返回 null r n 假設小明在很短的時間內發出10個請求,如果用單執行緒來乙個處理乙個,那麼這些請求會在佇列裡依次處理。假設乙個請求響應時間是10ms,那麼第二個請求響應時間將會為20ms 等第...

多執行緒伺服器

posix執行緒庫 a 與執行緒有關的函式都構成了乙個完整的系列,絕大多數函式的名字都是以 pthread 打頭的。b 要使用這些庫函式,要引入標頭檔案。c 鏈結這些執行緒庫函式時要使用編譯命令的 lpthread 選項。int pthread create pthread t thread,con...

多執行緒時間伺服器

include stdafx.h include include include include include define port 8080 int x 1 void error char str dword winapi new client proc lpvoid lpparam prin...