2015-05-02 49 views
1

我試圖從java服務器發送5個int到c客戶端。從java發送int到c

這裏是我的Java代碼:

class Server { 
public static void main(String args[]) throws Exception { 
ServerSocket welcomeSocket = new ServerSocket(8080); 

while(true) 
{ 
    Socket connectionSocket = welcomeSocket.accept(); 

    System.out.println("welcomeSocket.accept() called"); 
    DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); 

    outToClient.writeInt(1); 
    outToClient.writeInt(2); 
    outToClient.writeInt(3); 
    outToClient.writeInt(4); 
    outToClient.writeInt(5); 
    outToClient.close(); 
    connectionSocket.close(); 
} 
    } 
} 

這裏是我的C代碼:

// the function below is made by made, it creates and return a socket 
// AF_INET witch a tcp protocol 
int sock = socketClient("localhost",8080); 
if (sock < 0) { 
    printf("client : erreur socketClient\n"); 
    exit(2); 
} 

char intBufferCoupReq[20]; 

int data = recv(sock, intBufferCoupReq, 80, 0); 
printf("data recieved : %d\n",data); 
if(data == -1){ 
    printf("Error while receiving Integer\n"); 
} 

char intBufferCoupReq2[5][4]; 

int cpt; 
int j; 
int i = j = 0; 

// in this loop I divide my big array of 5 ints into 5 differents 
// array to use with ntohl 
for(cpt = 0; cpt < 20 ; cpt++){ 
    if(cpt%5==0) i=0; 
    if(j%4==0) j=0; 

    intBufferCoupReq2[i][j] = intBufferCoupReq[cpt]; 
    i++; 
    j++; 


} 

int receivedInt[5]; 
for(cpt=0;cpt<5;cpt++){ 
    printf("int n°%d = %d\n",cpt+1,ntohl(*((int *) &intBufferCoupReq2[cpt]))); 
} 


close(sock); 

第一次C客戶機發出請求它是有點兒罰款:

data recieved : 20 
int n°1 = 4 
int n°2 = 3 
int n°3 = 2 
int n°4 = 1 
int n°5 = 5 

但第二次(沒有關閉服務器)我得到這個:

data recieved : 8 
int n°1 = 16384 
int n°2 = -1610612736 
int n°3 = 11010050 
int n°4 = -1342118655 
int n°5 = 524519 

而我的java服務器崩潰與「連接重置」錯誤。 這兩個程序運行在同一臺計算機上的本地主機,端口8080.

我一直在試圖弄清楚這幾天,但我真的無能爲力。 你們有沒有得到一個建議?

非常感謝!

回答

2

在你的C程序,請更換:

char intBufferCoupReq[20]; 

int data = recv(sock, intBufferCoupReq, 80, 0); 
printf("data recieved : %d\n",data); 
if(data == -1){ 
    printf("Error while receiving Integer\n"); 
} 

有了:

char intBufferCoupReq[1024]; 
memset(intBufferCoupReq, '\0', sizeof(intBufferCoupReq)); 

int k = 0; 
while (1) { 
    int nbytes = recv(sockfd, &intBufferCoupReq[k], 1, 0); 
    if (nbytes == -1) { printf("recv error\n"); break; } 
    if (nbytes == 0) { printf("recv done\n"); break; } 
    k++; 
} 

這樣做是爲了確保服務器發送的所有數據包都正確接收。

更新:添加代碼以確認下面收到的數據。 Java程序以網絡字節順序發送整數,這需要轉換爲主機字節順序。

int *myints = (int*) intBufferCoupReq; 
int i = 0; 
for (i=0; i<(k/4); i++) { 
    printf("myints[%d]=%d\n", i, ntohl(myints[i])); 
} 
+0

它的工作非常感謝。 幫了我很多。 我只有幾個問題: 您將數組「intBufferCoupReq」大小設置爲1024位。 它是大的方式不是嗎? 是否確保數組足夠長? 爲什麼我按順序收到整數? (4 3 2 1 5)當我的服務器發送它的順序(1 2 3 4 5)? 再次感謝! – Sherokan

+0

是的,最好有大的緩衝區。 1024字節(不是位)不是太大。這是爲了防止服務器發生錯誤併發送超過緩衝區大小的預防措施。在TCP中,收到的訂單必須與發送的訂單相同。請再檢查一次。 – tivn

+0

請參閱我的編輯,其中包含額外的代碼以確認收到的數據。 – tivn