c++ linux socket程式設計 c++網路程式設計
阿新 • • 發佈:2019-01-10
宣告:大部分程式碼來自這篇部落格http://www.cnblogs.com/diligenceday/p/6241021.html, 感謝博主
思路:
思路很重要呦~~~
socket詳細資訊,思路:http://www.cnblogs.com/renfanzi/p/5713054.html
基礎知識
一個簡單的socket服務端和客戶端
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #includesimple server<netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <iostream> #include <string> #include <typeinfo> #define PORT 7000 #define QUEUE 20 int conn; using namespace std; int main() {//例項化socket物件: // AF_INET為地址簇,預設IPV4; // SOCK_STREAM為型別,預設為tcp // 0為協議,預設自動選擇合適協議 int ss = socket(AF_INET, SOCK_STREAM, 0); // 建立一個struct struct sockaddr_in server_sockaddr; //結構體加入引數:埠和地址 server_sockaddr.sin_family = AF_INET; server_sockaddr.sin_port = htons(PORT); server_sockaddr.sin_addr.s_addr= htonl(INADDR_ANY); //bind() if (bind(ss, (struct sockaddr *) &server_sockaddr, sizeof(server_sockaddr)) == -1) { perror("bind"); exit(1); } //listen() if (listen(ss, QUEUE) == -1) { perror("listen"); exit(1); } struct sockaddr_in client_addr; socklen_t length = sizeof(client_addr); //accept() //成功返回非負描述字,出錯返回-1 conn = accept(ss, (struct sockaddr *) &client_addr, &length); if (conn < 0) { perror("connect"); exit(1); } char buffer[1024]; while (1) { memset(buffer, 0, sizeof(buffer)); //read() int len = recv(conn, buffer, sizeof(buffer), 0); if (strcmp(buffer, "exit\n") == 0) break; printf("buffer: %s", buffer); //send() //必須要有返回資料, 這樣才算一個完整的請求 send(conn, buffer, len, 0); } close(conn); close(ss); return 0; }
#include <sys/types.h> #include <sys/socket.h> #include <stdio.h> #include <netinet/in.h> #include <arpa/inet.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <fcntl.h> #include <sys/shm.h> #define MYPORT 7000 #define BUFFER_SIZE 1024 int main() { ///定義sockfd int sock_cli = socket(AF_INET, SOCK_STREAM, 0); ///定義sockaddr_in struct sockaddr_in servaddr; memset(&servaddr, 0, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(MYPORT); ///伺服器埠 servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); ///伺服器ip //連線伺服器,成功返回0,錯誤返回-1 if (connect(sock_cli, (struct sockaddr *) &servaddr, sizeof(servaddr)) < 0) { perror("connect"); exit(1); } char sendbuf[BUFFER_SIZE]; char recvbuf[BUFFER_SIZE]; while (fgets(sendbuf, sizeof(sendbuf), stdin) != NULL) { send(sock_cli, sendbuf, strlen(sendbuf), 0); ///傳送 if (strcmp(sendbuf, "exit\n") == 0) break; recv(sock_cli, recvbuf, sizeof(recvbuf), 0); ///接收 fputs(recvbuf, stdout); memset(sendbuf, 0, sizeof(sendbuf)); memset(recvbuf, 0, sizeof(recvbuf)); } close(sock_cli); return 0; }simple client
還沒寫完呢,下一步,1對多,多執行緒,非同步,開源庫,框架,等等...