server.cpp
#include #include #include #include #include #include #include #include #include #include #include #include #include #define ip "127.0.0.1"
#define port 8888
int main(int argc, char* ar**)
//防止埠復用
int reuse = 1 ;
setsockopt(sfd, sol_socket, so_reuseaddr, (void*)&reuse, sizeof(reuse));
//初始化socket
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = af_inet;
servaddr.sin_port = htons(port) ;
servaddr.sin_addr.s_addr = inet_addr(ip);
//繫結套接字
if(bind(sfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1)
//監聽套接字
if(listen(sfd, 5) == -1)
//連線確認
if((afd = accept(sfd, null, null)) == -1)
char buf[1024];
while(memset(buf, 0, 1024), read(afd, buf, 1024))
} //關閉套接字
close(afd);
return 0;
}
client.cpp
#include #include #include #include #include #include #include #include #include #include #include #include #include #define ip "127.0.0.1"
#define port 8888
int main(int argc, char* ar**)
//防止埠復用
int reuse = 1 ;
setsockopt(sfd, sol_socket, so_reuseaddr, (void*)&reuse, sizeof(reuse));
//設定將要與伺服器連線的套接字
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = af_inet;
servaddr.sin_port = htons(port) ;
servaddr.sin_addr.s_addr = inet_addr(ip);
//與伺服器連線
if(connect(sfd, (sockaddr*)&servaddr, sizeof(servaddr))== -1)
//通訊
char buf[1024];
while(memset(buf, 0, 1024), scanf("%s", buf) != eof) }
close(sfd);
return 0;
}
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 客戶 伺服器程式示例
1 client 從標準輸入讀入一行文字,並寫給伺服器。2 伺服器從網路輸入讀入這行文字,並回射給客戶。3 客戶從網路輸入讀入這行回射的文字,顯示在標準輸出上 標準輸入 fgets tcp 客戶 write read tcp 伺服器 標準輸出 fputs tcp 客戶 read write tcp ...
TCP客戶 伺服器程式示例
1.tcp回射示例 伺服器 include include include include include include in.h define srv port 8888 define maxline 4096 void str echo int fd int main int argc,cha...