簡體   English   中英

從套接字讀取時出現問題

[英]Trouble while reading from socket

我正在嘗試從套接字讀取字符; 這是我為此創建的函數,主要是從Here那里得到啟發的, 這里我刪除了一些不相關的部分(此示例正在正確編譯)。

int process(int socketfd, void *buffer, int n)
{
  int totread = 0;
  char ch;
  int numread;

  for(;;)
  {
    numread = read(socketfd, &ch, 1);

    if(numread == 0) {
        if (totread == 0) {
            return 0;
        } else {
            break;
        }
    } else {
        if(totread < n-1) {
            totread++;
            printf("totread: %d\n", totread);
            printf("Here is OK, ch value gets printed %c\n", ch);
            *buffer++ = ch;
            printf("With help provided, this line gets printed\n");
            printf("But the value <%s> of buffer, is blank (<> output)\n, buffer);
        }
        if (ch == '\n') {
            printf("%c\n", ch);
            printf("%s\n", buffer);
            break;
        }
    }
}
return totread;
}

我不明白為什么第二行沒有打印。 顯然, *buf++ = ch指令有錯誤; 但這看起來是正確的。 它只是影響讀取到字符buf數組下一個值的字符。 我在編譯時沒有看到錯誤或警告,打印第一行后客戶端斷開連接,而第二行未到達。

編輯

這是初始化緩沖區的方法:

char *buffer = "";
int l = process(newsockfd, buffer, 100);
printf("Number read (function network) %d\n", l);

這可能不是合適的方法。 我也嘗試過指定固定長度,例如char buffer = [255]; 該功能不會退出,但不會打印任何內容。 我是C編程的新手,非常感謝您的幫助!

int process(..., void * b, ...
{
  ...

  *b++ = ...

void引用和/或增加void指針無效C。編譯器至少應對此發出警告。

重新打開所有警告(對於gcc,請通過選項-Wall -Wextra -pedantic來編譯代碼)。 然后修復代碼,直到不再發出警告。


參考您有關如何調用該函數的編輯內容:

這個

char *buffer = "";

不聲明緩沖區,而只是聲明一個指針。 該指針指向大小為1的字符串文字。 字符串文字根據定義為常量。

總結一下:您向您的process()函數提供了一個指向大小為1常量內存的指針。

問題:

  1. 您無法讀入常量內存。
  2. 即使1.不適用,您也只能讀入1個字節。

要解決此問題,請更改代碼,如下所示:

char buffer[100] = ""; /* Define a buffer of 100 characters size and 
                          initialise it to all `0`s. */
int l = process(newsockfd, buffer, 100);

按照process()阻塞,您需要查看read()函數:如果調用了該函數,但是發件人不發送任何東西,只要連接仍然正常,它就不會返回。

並且:使process()處理作為n傳入的值。

嘗試將第一行更改為char * buf =(char *)緩沖區; 並在-Werror上使用gcc進行編譯

暫無
暫無

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

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