網路抓來的範例程式再加點小修改,client連上server後,server送"Hi client!"給client。client收到後,再回傳"receiveack"給server表示收到。

server程式:


#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
int main()
{
    int sockfd;
    struct sockaddr_in dest;
    char buffer[20] = "Hi client! ";
    char buffer1[10];
    /* create sockett */
    sockfd = socket(PF_INET, SOCK_STREAM, 0);

    /* initialize structure dest */
    bzero(&dest, sizeof(dest));
    dest.sin_family = AF_INET;
    dest.sin_port = htons(8889);
    /* this line is different from client */
    dest.sin_addr.s_addr = INADDR_ANY;

    /* Assign a port number to socket */
    bind(sockfd, (struct sockaddr*)&dest, sizeof(dest));

    /* make it listen to socket with max 20 connections */
    listen(sockfd, 20);

    /* infinity loop -- accepting connection from client forever */
    while(1)
    {
        int clientfd;
        struct sockaddr_in client_addr;
        int addrlen = sizeof(client_addr);

        /* Wait and Accept connection */
        clientfd = accept(sockfd, (struct sockaddr*)&client_addr, &addrlen);

        /* Send message */
        send(clientfd, buffer, sizeof(buffer), 0);
        int res=recv(clientfd, buffer1, sizeof(buffer1), 0);
        printf("receive from client: %s, %d bytes\n", buffer1,res);
        //write(fd, buffer1, sizeof(buffer1));
        /* close(client) */
        close(clientfd);
    }

    /* close(server) , but never get here because of the loop */
    close(sockfd);
    return 0;
}

 

client程式:

#include <sys/types.h>          /* See NOTES */
#include <sys/socket.h>
#include <netinet/in.h>
#include <strings.h>
#include <stdio.h>
int main()
{
    int sockfd;
    struct sockaddr_in dest;
    char buffer[128];
    char resp[10]="clientack";

    /* create socket */
    sockfd = socket(PF_INET, SOCK_STREAM, 0);

    /* initialize value in dest */
    bzero(&dest, sizeof(dest));
    dest.sin_family = PF_INET;
    dest.sin_port = htons(8889);
    dest.sin_addr.s_addr = inet_addr("127.0.0.1");
    //inet_aton("127.0.0.1", &dest.sin_addr);

    /* Connecting to server */
    connect(sockfd, (struct sockaddr*)&dest, sizeof(dest));

    /* Receive message from the server and print to screen */
    bzero(buffer, 128);
    recv(sockfd, buffer, sizeof(buffer), 0);
    printf("receive from server: %s\n", buffer);
    send(sockfd,resp,sizeof(resp),0);
    /* Close connection */
    close(sockfd);

    return 0;
}

執行結果:

latrell:~/temp/ctest$ ./server
receive from client: clientack, 10 bytes

latrell:~/temp/ctest$ ./client
receive from server: Hi client!

 

 

 

 

kezeodsnx 發表在 痞客邦 PIXNET 留言(1) 人氣()


留言列表 (1)

發表留言
  • 吳振宇
  • root@raspberrypi:~# ./server.c
    ./server.c: line 8: syntax error near unexpected token `('
    ./server.c: line 8: `int main()'

    我複製貼上執行錯誤