SocketClient.c 1.46 KB
Newer Older
1 2 3 4 5 6 7 8 9
#include "../lib/sock_msg.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

马伊齐's avatar
马伊齐 committed
10
#define PORT 8888 // 服务器端口号
马伊齐's avatar
马伊齐 committed
11
#define IP "172.27.92.202"
12 13 14 15 16

int main(int argc, char *argv[])
{
    int sockfd;                  // 连接套接字
    struct sockaddr_in servaddr; // 服务器地址结构
马伊齐's avatar
马伊齐 committed
17
    char buf[BUFFER_SIZE];       // 缓冲区
18 19 20 21 22 23 24
    int n;                       // 读写字节数

    // 创建连接套接字,使用TCP协议
    inet_pton(AF_INET, IP, &servaddr.sin_addr);
    sockfd = sock_init(0, servaddr.sin_addr.s_addr, PORT);

    // 循环从标准输入读取数据,并发送给服务器,然后接收服务器的回复,并打印
马伊齐's avatar
马伊齐 committed
25
    while (fgets(buf, BUFFER_SIZE, stdin) != NULL)
26
    {
马伊齐's avatar
马伊齐 committed
27 28 29 30 31 32
        if (strncmp(buf, "exit\n", 4) == 0)
        {
            printf("Close the connection.\n");
            break;
        }
        printf("send: %s\n", buf);
33
        sock_write(sockfd, buf, strlen(buf)); // 发送数据
马伊齐's avatar
马伊齐 committed
34 35 36 37
        // 清空buf
        memset(buf, 0, BUFFER_SIZE);
        printf("recv: %s\n", buf);
        n = sock_read(sockfd, buf, BUFFER_SIZE); // 接收数据
38 39 40 41 42 43 44 45 46
        if (n == 0)
        {
            printf("the other side has been closed.\n");
            break;
        }
        write(STDOUT_FILENO, buf, n); // 打印数据
    }

    // 关闭连接套接字
马伊齐's avatar
马伊齐 committed
47
    sock_exit(sockfd);
48 49 50

    return 0;
}