Linux系统QT编写简单C++ 的C/S (socket连接)

1)Client.cpp

#include
#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096

int main(int argc, char** argv){
     int   sockfd, n;
     char  recvline[4096], sendline[4096];
     struct sockaddr_in  servaddr;

     if( argc != 2){
         printf("usage: ./client \n");
         return 0;
     }

     if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0){
         printf("create socket error: %s(errno: %d)\n", strerror(errno),errno);
         return 0;
     }

     memset(&servaddr, 0, sizeof(servaddr));
     servaddr.sin_family = AF_INET;
     servaddr.sin_port = htons(6666);
     if( inet_pton(AF_INET, argv[1], &servaddr.sin_addr) <= 0){
         printf("inet_pton error for %s\n",argv[1]);
         return 0;
     }

     if( connect(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) < 0){
         printf("connect error: %s(errno: %d)\n",strerror(errno),errno);
         return 0;
     }

     printf("send msg to server: \n");
     fgets(sendline, 4096, stdin);
    if( send(sockfd, sendline, strlen(sendline), 0) < 0){
         printf("send msg error: %s(errno: %d)\n", strerror(errno), errno);
         return 0;
     }
     close(sockfd);
     return 0;
 }

2)Serve.cpp

#include
#include
#include
#include
#include
#include
#include
#include
#define MAXLINE 4096

int main(int argc, char** argv)
{
    int  listenfd, connfd;
    struct sockaddr_in  servaddr;
    char  buff[4096];
    int  n;

    if( (listenfd = socket(AF_INET, SOCK_STREAM, 0)) == -1 ){
         printf("create socket error: %s(errno: %d)\n",strerror(errno),errno);
         return 0;
     }

     memset(&servaddr, 0, sizeof(servaddr));
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(6666);

    if( bind(listenfd, (struct sockaddr*)&servaddr, sizeof(servaddr)) == -1){
        printf("bind socket error: %s(errno: %d)\n",strerror(errno),errno);
        return 0;
     }

    if( listen(listenfd, 10) == -1){
         printf("listen socket error: %s(errno: %d)\n",strerror(errno),errno);
         return 0;
     }

     printf("======waiting for client's request======\n");
     while(1)
     {
        if( (connfd = accept(listenfd, (struct sockaddr*)NULL, NULL)) == -1){
             printf("accept socket error: %s(errno: %d)",strerror(errno),errno);
             continue;
         }
         n = recv(connfd, buff, MAXLINE, 0);
         buff[n] = '\0';
         printf("recv msg from client: %s\n", buff);
         close(connfd);
     }
     close(listenfd);
     return 0;
 }

3)运行Serve,Client
4)连接通信
(1)起动两个控制台,分别转到Serve、Client所在文件夹下
(2)启动服务器:$ ./Serve
(3)启动客户端:$ ./Client 127.0.0.1

Linux系统QT编写简单C++ 的C/S (socket连接)_第1张图片

你可能感兴趣的:(Linux)