C++ socket编程实例
生活随笔
收集整理的這篇文章主要介紹了
C++ socket编程实例
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
服務(wù)器端:
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> #include <iostream> #include <arpa/inet.h> #include <unistd.h>using namespace std;typedef unsigned char uchar;int main() {//build the socket for serverint s = socket(AF_INET, SOCK_STREAM, 0);//bind the socket to addressstruct sockaddr_in adr_s;adr_s.sin_family = AF_INET;adr_s.sin_addr.s_addr = inet_addr("127.0.0.1");adr_s.sin_port =htons(1235);bind(s, (struct sockaddr *)&adr_s, sizeof(adr_s));//listenlisten(s, 20);//accept the request from client//build the socket for client, system can bind local address to it automaticallystruct sockaddr_in adr_c;socklen_t c_size = sizeof(struct sockaddr_in);int c= accept(s, (struct sockaddr *)&adr_c, &c_size);/*char str[] = "Hello World!"; // apply for a space for the received dataint recv_result = write(c, str, sizeof(str));cout<<"recv_result is:"<<recv_result<<endl;*/char buffer[BUFSIZ];int len;while((len = recv(c, buffer, BUFSIZ, 0))>0){buffer[len] = '\0';printf("recv string is:%s\n", buffer);if(send(c, buffer, len*sizeof(char), 0)<0)perror("send");}close(s);close(c);return 0;}客戶端:
#include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <stdio.h> # include <string.h> #include <iostream> #include <arpa/inet.h>#include <unistd.h>using namespace std;typedef unsigned char uchar;int main() {//build a socket for the clientint c = socket(AF_INET, SOCK_STREAM, 0);//build a socket for the serverint s = socket(AF_INET, SOCK_STREAM, 0); //the struct for the address of the serverstruct sockaddr_in adr_s;adr_s.sin_family = AF_INET;adr_s.sin_addr.s_addr = inet_addr("127.0.0.1");adr_s.sin_port =htons(1235);bind(s, (struct sockaddr *)&adr_s, sizeof(adr_s));//connect to the socket of the server.if(connect(c, (struct sockaddr*)&adr_s, sizeof(adr_s))<0)perror("connect");/*char buffer[40];read(c, buffer, sizeof(buffer)-1);printf("Message form server: %s\n", buffer);*/char buffer[BUFSIZ];int len;while(1){printf("input a string:");scanf("%s", buffer);if(send(c, buffer, strlen(buffer)*sizeof(char), 0)<0)perror("send");if((len = recv(c, buffer, BUFSIZ*sizeof(char), 0))<0)perror("recv");buffer[len] = '\0';printf("recv string is:%s\n", buffer);}close(c);return 0; }總結(jié)
以上是生活随笔為你收集整理的C++ socket编程实例的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: jdk6安装
- 下一篇: UEditor编辑器保存数据到数据库