簡體   English   中英

將數據從服務器發送到客戶端套接字編程

[英]Sending data from server to client socket programming

我剛剛開始學習套接字編程。

當前,服務器和客戶端在同一工作站上,一切似乎都可以正常工作。 服務器正在用C編程運行,我的客戶端是一個android程序。 我設法建立了一種單向連接,將數據從客戶端發送到服務器。 我想將一些字符串發回給客戶

請給我建議。

void *connection_handler(void *);

int main(int argc , char *argv[])
{
    int socket_desc , client_sock , c;
    struct sockaddr_in server , client;

    //Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 7800 );

    //Bind
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        //print the error message
        perror("bind failed. Error");
        return 1;
    }
    puts("bind done");

    //Listen
    listen(socket_desc , 3);

    //Accept and incoming connection
    //puts("Waiting for incoming connections...");
    //c = sizeof(struct sockaddr_in);


    //Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);
    pthread_t thread_id;

    while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
    {
        puts("Connection accepted");

        if( pthread_create( &thread_id , NULL ,  connection_handler , (void*) &client_sock) < 0)

        {
            perror("could not create thread");
            return 1;
        }

        //Now join the thread , so that we dont terminate before the thread
        //pthread_join( thread_id , NULL);
        puts("Handler assigned");
    }

    if (client_sock < 0)
    {
        perror("accept failed");
        return 1;
    }

    return 0;
}

/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[2000];

    //Send some messages to the client
    message = "Greetings! I am your connection handler\n";
    write(sock , message , strlen(message));

    message = "Now type something and i shall repeat what you type \n";
    write(sock , message , strlen(message));

    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        //end of string marker
        client_message[read_size] = '\0';

        printf("%s\n", client_message);

        //Send the message back to client
        write(sock , client_message , strlen(client_message));

        //clear the message buffer
        memset(client_message, 0, 2000);


    }

    if(read_size == 0)
    {
        //puts("Client disconnected");

        //fflush(stdout);
    }
    else if(read_size == -1)
    {
        perror("recv failed");
    }

    return 0;
} 

有多種方法可以將數據傳輸到另一個套接字,無論是服務器還是客戶端都沒有關系。

就像您在代碼中所做的那樣,您可以使用系統調用:

ssize_t write(int fd, const void *buf, size_t count);

它從buf寫入與文件描述符fd相關的文件。 返回值將告訴您消息是否正確發送。

發送,發送到,發送消息

這是將數據發送到套接字的第二種方法。 writesend之間的唯一區別是參數flags

ssize_t send(int sockfd, const void *buf, size_t len, int flags);

但是如果將flag設置為0,則writesend將以相同的方式工作。 sendtosendmsgsend完全不同,因為它們具有更多參數。 您可以從在線或Linux中的手冊頁中獲取所有信息。

http://man7.org/linux/man-pages/man2/send.2.html

while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )

是錯的; 您可能想檢查>= 0或(甚至更好)用另一種方式表示。

孤獨的人

write(sock , message , strlen(message));

不好:

  1. 您應該檢查錯誤代碼
  2. 接收者很難分割結果。
  3. 當另一端關閉時, write()將使用SIGPIPE殺死您的程序

我建議類似

bool send_data(int fd, void const *data, size_t len) 
{
    while (len > 0) {
        ssize_t l = send(fd, data, len, MSG_NOSIGNAL);

        if (l > 0) {
            data += l;
            len -= l;
        } else if (l == 0) {
            fprintf(stderr, "this is ugly and can not happen...\n");
            break;
        } else if (errno == EINTR) {
            continue;
        } else {
            perror("send()");
            break;
        }
    }

    return len == 0;
}

和字符串數據類型

bool send_string(int fd, char const *str)
{
    size_t l = strlen(str);
    uint32_t  l_be = htobe32(l);

    if ((uint32_t)(l) != l)
        return false;

    return (send_data(fd, &l_be, sizeof l_be) &&
            send_data(fd, str, l));
}

對於接收,您可以類似於上面的send_data()實現recv_data() 根據您的內存分配策略,您可以實施

bool recv_string(int fd, char *str, size_t max_len, size_t *len)
{
    uint32_t  l_be;
    size_t l;

    if (!recv_data(fd, &l_be, sizeof l_be))
        return false;

    l = be32toh(l_be);
    if (l >= max_len)
        return false;

    if (!recv_data(fd, str, l))
        return false;

    str[l] = '\0';

    if (len)
        *len = l;

    return true;   
}

或在讀取長度后為接收的數據寫一些malloc()內存。

現在,您可以在一側進行操作:

if (!send_string(fd, "foo") ||
    !send_string(fd, "bar") ||
    !recv_string(fd, resp, sizeof resp, NULL))
       error();

另一個

if (!recv_string(fd, req0, sizeof req0, NULL) ||
    !recv_string(fd, req1, sizeof req1, NULL) ||
    !send_string(fd, handle_request(req0, req1)))
        error();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM