TCP連線實現 客戶端 服務端 通訊

2021-08-29 18:22:25 字數 2562 閱讀 4499

//客戶端 client.c

#include #include #include #include #include #include #include #include #define max_buf 512

int main(int argc, char *argv)

// 設定伺服器位址結構體

bzero(&server_addr, sizeof(server_addr)); // 初始化伺服器位址,保證最後8位元組為0

server_addr.sin_family = af_inet; // ipv4

server_addr.sin_port = htons(port); // 伺服器端口

//inet_pton(af_inet, server_ip, &server_addr.sin_addr); // 伺服器ip位址

server_addr.sin_addr.s_addr = inet_addr(server_ip);//伺服器ip位址,與inet_pton等價

printf("client: want to connect the server %s, server port %d\n",

inet_ntoa(server_addr.sin_addr), ntohs(server_addr.sin_port));

//發起連線(初始化套接字)

if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)

printf("connect success!\n");

while (1)

bzero(buf, max_buf + 1); //清空接收傳送緩衝區

printf("input the message to send:\n");

//從終端輸入訊息以傳送

fgets(buf, max_buf, stdin);

//退出迴圈條件,輸入quit可以退出通訊

if (!strncasecmp(buf, "quit", 4))

//傳送資料(send:連線套接字)

if (send(sockfd, buf, strlen(buf) - 1, 0) > 0)

printf("send success!\n");

else

}close(sockfd); //關閉socket物件

return 0;

}

//服務端 server.c

#include #include #include #include #include #include #include #include #define max_buf 512

int main(int argc, char *argv)

// 設定伺服器位址結構體

bzero(&server_addr, sizeof(server_addr)); // 初始化伺服器位址,保證最後8位元組為0

server_addr.sin_family = af_inet; // ipv4

server_addr.sin_port = htons(port); // 伺服器端口

//inet_pton(af_inet, server_ip, &server_addr.sin_addr); // 伺服器ip位址

server_addr.sin_addr.s_addr = inet_addr(server_ip);//伺服器ip位址,與inet_pton等價

//繫結ip位址與埠資訊(繫結套接字)

if (bind(sockfd, (struct sockaddr *)&server_addr, sizeof(struct sockaddr)) == -1)

//監聽網路(監控監聽套接字)

if (listen(sockfd, 10) == -1)

//等待客戶端連線

printf("wait for connect.\n");

len = sizeof(struct sockaddr);

//生成連線套接字

if ((new_fd = accept(sockfd, (struct sockaddr*)&client_addr, &len)) == -1) else

while (1)

//傳送資料(send:連線套接字)

if (send(new_fd, buf, strlen(buf) - 1, 0) > 0)

printf("send success!\n");

else

//接收資料

bzero(buf, max_buf + 1); //清空接收傳送緩衝區

//recv:連線套接字

if ((len = recv(new_fd, buf, max_buf, 0)) > 0) else

}close(sockfd); //關閉socket物件

close(new_fd);

return 0;

}

TCP通訊,多客戶端通訊(客戶端 服務端)

客戶端和伺服器間的交流,客戶端傳送資訊,伺服器接收到,並返回資訊 長連線建立socket連線服務端 指定ip位址,埠號 通過ip位址找對應的伺服器 呼叫socket的getinputstream 和getoutputstream 方法獲取和服務端相連的io流 輸入流可以讀取服務端輸出流寫出的資料 輸...

TCP客戶端與服務端通訊

客戶端 include include include include include in.h include include include include define maxline 1024 int main int argc,char ar 建立socketfd socketfd soc...

TCP客戶端服務端demo

服務端程式 include include include include include include include int main 列印握手成功的客戶端 struct sockaddr in servaddr socklen t nservlen sizeof servaddr getso...