2017-08-07 168 views
-2

執行後,我在客戶端鍵入文件名,但沒有打印到服務器端。已經嘗試了一切。請幫忙。我在Windows中使用bash。我只是從客戶端發送文件名到服務器。服務器端將顯示客戶端。消息未發送:C套接字

這是我client.c

#include<stdio.h> 
#include<sys/socket.h> 
#include<sys/types.h> 
#include<string.h> 
#include<netinet/in.h> 
#include<stdlib.h> 
#include<unistd.h> 
    int main() 
    { 
    int i,size,connect_status,sd; 
    char sentmsg[100],recvmsg[100]; 
    int sentlen,sent_status,recvlen,recvbytes; 
    struct sockaddr_in client,address; 
    sd = socket(AF_INET,SOCK_STREAM,0); 
    if(sd == -1) 
    { 
      perror("Socket Error : "); 
      return 0; 
    } 

    client.sin_family = AF_INET; 
    client.sin_port = htons(1543); 
    client.sin_addr.s_addr = INADDR_ANY; 
    for(i=0; i<8;i++) 
    { 
      client.sin_zero[i] = '\0'; 
    } 
    connect_status = connect(sd,(struct sockaddr*)&client,sizeof(struct sockaddr)); 
    if(connect_status == -1) 
    { 
      perror("Connect Error : "); 
      return 0; 
    } 
    printf("\nEnter the file name to be read : "); 
    scanf("%s",sentmsg); 
    sent_status = send(sd,sentmsg,100,0); 
    if(sent_status == -1) 
    { 
      perror("Sending Error : "); 
      return 0; 
    } 

    return 0; 
    } 

這是我server.c

#include<stdio.h> 
#include<sys/socket.h> 
#include<sys/types.h> 
#include<string.h> 
#include<netinet/in.h> 
#include<stdlib.h> 
#include<unistd.h> 
#include<fcntl.h> 
#include<sys/stat.h> 
int main() 
{ 
    int i,newsd,sd,size,listen_status,bind_status,fd; 
    char sentmsg[100],recvmsg[100]; 
    int sent_status,rec_status,sentlen,recvlen; 
    struct sockaddr_in server,address; 
    sd = socket(AF_INET,SOCK_STREAM,0); 
    if(sd == -1) 
    { 
      perror("Socket Error : "); 
      return 0; 
    } 
    server.sin_family = AF_INET; 
    server.sin_port = htons(1534); 
    server.sin_addr.s_addr = INADDR_ANY; 
    for(i=0 ; i<8 ; i++) 
    { 
      server.sin_zero[i] = '\0'; 
    } 
    bind_status = bind(sd,(struct sockaddr*)&server,sizeof(struct sockaddr)); 
    if(bind_status == -1) 
    { 
      perror("\nBind Error : "); 
      return 0; 
    } 
    listen_status = listen(sd,5); 
    if(listen_status == -1) 
    { 
      perror("\nListen Error : "); 
      return 0; 
    } 
    size = sizeof(struct sockaddr_in); 
    newsd = accept(sd,(struct sockaddr*)&address,&size); 
    if(newsd == -1) 
      { 
      perror("\nAccept Error : "); 
      return 0; 
    } 
    rec_status = recv(newsd,recvmsg,recvlen,0); 
    if(rec_status == -1) 
    { 
      perror("\nRecieve Error : "); 
      return 0; 
    } 
    recvmsg[rec_status] = '\0'; 
    printf("\nClient : %s",recvmsg); 
    return 0; 
} 

我unabble從客戶端發送消息到服務器。請幫忙

+0

拒絕連接意味着服務器主動拒絕連接請求。該端口是可訪問的,但沒有服務器進程限制。 –

+0

那麼我需要做什麼? –

+2

我對C中的網絡通信一無所知,但這是一個常見的錯誤。你已經在客戶機中定義了'client.sin_port = htons(1543);'但在服務器中,'server.sin_port = htons(1534);'這對你來說看起來是否正確?還是應該是同一個端口? –

回答

0

這是因爲你沒有初始化recvlen。 將其設置爲接收緩衝區長度,它將工作:

recvlen = 100; 
rec_status = recv(newsd,recvmsg,recvlen,0);