TCP通訊應用例項 伺服器與單個客戶端通訊

2021-10-24 11:22:33 字數 2471 閱讀 8960

更多資料:我的目錄

執行結果:

伺服器部分:

客戶端部分:

伺服器部分 :

/*

伺服器部分:

*/#include

#include

#include

#include

#include

#include

#include

int tcpsock;

int newsock;

void

finish()

void

*transfer()

;//存放客戶端傳送給指定客戶端的訊息

while(1

)printf

("receive %s\n"

,buf);}

}int

main()

int on=1;

setsockopt

(tcpsock,sol_socket,so_reuseaddr,

&on,

sizeof

(on));

//設定埠釋放後立即就可以被再次使用

ret=

bind

(tcpsock,

(struct sockaddr *

)&bindaddr,

sizeof

(bindaddr));

//繫結ip和埠號

if(ret==-1

) ret=

listen

(tcpsock,8)

;//監聽

if(ret==-1

)signal

(sigint,finish)

;while(1

)printf

("ip == %s\n"

,inet_ntoa

(clientaddr.sin_addr));

printf

("埠號 == %d\n"

,ntohs

(clientaddr.sin_port));

printf

("新的檔案描述符:%d\n"

,newsock);

pthread_t id;

pthread_create

(&id,

null

,&transfer,

null);

}}

客戶端部分:

/*

客戶端部分:

*/#include

#include

#include

#include

#include

#include

#include

int tcpsock;

pthread_t id;

void

*fun()

printf

("receive %s\n"

,recv);}

}}void

finish()

intmain()

int on=1;

setsockopt

(tcpsock,sol_socket,so_reuseaddr,

&on,

sizeof

(on));

//設定埠釋放後立即就可以被再次使用

ret=

bind

(tcpsock,

(struct sockaddr *

)&bindaddr,

sizeof

(bindaddr));

//繫結ip和埠號

if(ret==-1

) ret=

connect

(tcpsock,

(struct sockaddr *

)&serveraddr,

sizeof

(serveraddr));

//連線伺服器

if(ret==-1

)signal

(sigint,finish)

;pthread_create

(&id,

null

,&fun,

null);

printf

("請輸入要傳送給伺服器的資訊!\n");

//傳送資訊給伺服器

while(1

)write

(tcpsock,buf,

strlen

(buf));

}close

(tcpsock)

;return0;

}

TCP伺服器通訊

tcp協議的通訊流程 單程序版本的server.c 伺服器主要用到的埠 聽myaddr所描述的位址和埠號。accept 典型的伺服器程式可以同時服務於多個客戶端,當有客戶端發起連線時,伺服器呼叫的accept 返回並接受這個連線,如果有大量的客戶端發起連線而伺服器來不及處理,尚未accept 的客戶...

TCP客戶 伺服器程式例項

1.概述 這章的tcp客戶 伺服器模型 2.tcp回射伺服器程式 1 main函式 include unp.h int main int argc,char argv close connfd parent closes connected socket 2 str echo函式 include u...

TCP客戶 伺服器程式例項

server.cpp include include include include include include include include include include include include include define ip 127.0.0.1 define port 888...