LINUX利用多執行緒完成多個客戶端向伺服器傳送資料

2021-09-30 13:58:19 字數 2833 閱讀 8423

標頭檔案:

#ifndef _myhead_h_

#define _myhead_h_

#include

#include

#include

#include

#include

#include

#include

#include

#define myport 6667   //1024以下的是保留的埠號,用大於1024的;

//#define myaddr "192.168.1.102"

#endif

伺服器程式:

#include "myhead.h"

void *read_msg(void *argc);

int main()

;     //變數型別儲存在netinet/in.h裡面的;

struct sockaddr_in sock_client = ;   //儲存連線的客戶端那邊的資訊;

socklen_t len = sizeof(struct sockaddr);

//第一步:建立套接字;

socketfd = socket(af_inet,sock_stream,0);

if(socketfd == -1)

printf("socket success...\n");     //確保前面的**是執行正確的;

//第二步:給套接字繫結必要的資訊;

sock_server.sin_family = af_inet;    //給服務程式繫結位址族;

sock_server.sin_port = htons(myport);   //給伺服器程式設定個埠號;

// sock_server.sin_addr.s_addr = inet_addr(myaddr);//給服務程式繫結ip位址;

sock_server.sin_addr.s_addr = htonl(inaddr_any);//繫結任意ip位址;

ret = bind(socketfd,(struct sockaddr *)&sock_server,sizeof(struct sockaddr));

if(ret == -1)

printf("bind success..\n");

ret = listen(socketfd,10);

if(ret == -1)

printf("listen success...\n");

// clientfd = accept(socketfd,(struct sockaddr *)&sock_client,&len);

// if(clientfd == -1)

// // printf("accept success...clinet fd = %d\n",clientfd);

char recvbuff[20] = ;

int recvcnt = 0;

printf("sizeof(struct sockaddr) = %d\n",sizeof(struct sockaddr));

printf("sizeof(struct sockaddr_in) = %d\n",sizeof(struct sockaddr_in));

while(1)

printf("accept success... clientfd = %d\n",clientfd); //4

ret = pthread_create(&th,null,read_msg,&clientfd);  //傳遞clientfd;要知道從哪乙個客戶端來讀取資料;

if(ret != 0)

} close(socketfd);

return 0; }

void *read_msg(void *argc) ;

int recvcnt = 0;

while(1)

else if(recvcnt == 0)

else

if(strcmp(recvbuff,"end") == 0)

} close(fd);

return null; }

客戶端程式:

#include "myhead.h"

//int main()

int main(int argc,char **ar**)

int socketfd = 0;

int ret = 0;

struct sockaddr_in sock_server = ;

socketfd = socket(af_inet,sock_stream,0);

if(-1 == socketfd)

printf("socket success...\n");

sock_server.sin_family = af_inet;

sock_server.sin_port = htons(myport);

// sock_server.sin_addr.s_addr = inet_addr(myaddr);

sock_server.sin_addr.s_addr = inet_addr(ar**[1]);

ret = connect(socketfd,(struct sockaddr *)&sock_server,sizeof(struct sockaddr));

if(ret == -1)

char sendbuff[20] = ;

int sendcnt = 0;

int action;

int toid;

struct message msg = ;

while(1)

else

} return 0; }

python多執行緒完成多個任務

執行緒 執行緒可以理解成執行 的分支,執行緒是執行對應的 的,cpu排程執行緒去執行對應 importtime importthreading 跳舞的任務 defdance 獲取當前執行 的執行緒 current thread threading.current thread print dance...

C 多執行緒 8 執行緒完成數

目錄假如,程式需要向乙個 web 傳送 5 次請求,受網路波動影響,有一定機率請求失敗。如果失敗了,就需要重試。示例 如下 class program console.writeline 任務執行完畢 模擬網路請求 完成一次任務,1 interlocked.add ref count,1 conso...

完成的多執行緒的例子

給我乙個完成的多執行緒的例子,裡面只要能實現乙個功能就ok了,希望能有詳細的注釋 using system using system.collections.generic using system.linq using system.text using system.threading name...