有一個簡單的客戶端 - 服務器程序。無法理解read()系統調用
- 服務器啓動$。/服務器5000
- 客戶端也被連接到服務器.. $。/客戶端127.0.0.1 5000
- 客戶端進入一個字符串
- 客戶端有消息「我有你的消息」,他的終端上顯示&服務器客戶端顯示輸入的字符串
的問題是,當我做$運行客戶端。/客戶127.0.0.1 5000我在服務器端得到這個終奌站。
Before Listen
After Listen
Before accept
After accept
Before read
然後只有當我在客戶端屏幕上輸入消息,然後按回車。我得到這個顯示..
Here is the message: This is a message
爲什麼是代碼進入等待 狀態之前閱讀()調用..不如果它 剛讀什麼,並返回0 ..
我在某個地方在概念上是錯的。請幫助我..
客戶端的相關代碼: -
if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0)
error("ERROR connecting");
printf("Please enter the message: ");
bzero(buffer,256);
fgets(buffer,255,stdin);
n = write(sockfd,buffer,strlen(buffer));
if (n < 0)
error("ERROR writing to socket");
bzero(buffer,256);
n = read(sockfd,buffer,255);
printf("%d\n",n);
if (n < 0)
error("ERROR reading from socket");
printf("%s\n",buffer);
相關的服務器代碼: -
if (bind(sockfd, (struct sockaddr *) &serv_addr,
sizeof(serv_addr)) < 0)
error("ERROR on binding");
printf("Before Listen ");
listen(sockfd,5);
printf("After Listen ");
clilen = sizeof(cli_addr);
printf("Before accept ");
newsockfd = accept(sockfd,
(struct sockaddr *) &cli_addr,
&clilen);
printf("After accept");
if (newsockfd < 0)
error("ERROR on accept");
bzero(buffer,256);
printf("Before read");
n = read(newsockfd,buffer,255);
if (n < 0) error("ERROR reading from socket");
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0) error("ERROR writing to socket");
我們輸入了幾乎相同的答案:) +1 – 2010-04-02 13:49:40
ohk。我不知道這個.. Thanx .. – 2010-04-02 13:57:13