[問題] socket 漏接??

看板java作者 (歐歐耶)時間14年前 (2011/08/13 13:56), 編輯推噓1(105)
留言6則, 3人參與, 最新討論串1/1
各位好! 小弟想用socket來傳送檔案 但是server端好像會漏接訊息!? 我是把檔案包成另一個byte檔 方便分辨收到的檔案 client傳檔code如下 DataOutputStream daout = new DataOutputStream(new BufferedOutputStream(clientSocket.getOutputStream())); daout.flush(); //讀檔路徑為傳進來的String path FileInputStream fis = new FileInputStream(path);//讀檔 byte[] sendName = myPackage.mypackage_cli(null, -1, fileName );//檔名的封包 daout.write(sendName, 0, sendName.length); byte[] buf=new byte[2043];//因為要加上封包的長度5 int num = fis.read(buf); while (num != ( - 1)) { //是否讀完文件 //Thread.sleep(10); byte[] send = myPackage.mypackage_cli(buf, -2, null ); daout.write(send, 0, send.length); daout.flush(); num = fis.read(buf); //繼續從檔案中讀取資料 } byte[] send2 = myPackage.mypackage_cli(null, -3, "end");//告知完成 關檔 daout.write(send2, 0, send2.length); fis.close(); 接收方面(server) DataInputStream dataInStream = new DataInputStream(new BufferedInputStream (socket.getInputStream())); ByteArrayOutputStream byteArrOutStream = new ByteArrayOutputStream(); byte[] byteBuf = new byte[5000]; int current = 0 , readlength ; //當Socket已連接時連續執行 while(socket.isConnected()) { // 取得網路串流的訊息 int ln; while(( ln = dataInStream.read(byteBuf)) != -1){ byteArrOutStream.write(byteBuf, 0, ln); byte[] receivedData = byteArrOutStream.toByteArray();//把array收進來 readlength = myPackage.byteArrayToInt(receivedData, current+1); switch(receivedData[current]){//抓第一個byte分析是哪種型態 //用這樣的方法傳給其他client default: out = new DataOutputStream(new BufferedOutputStream (socket.getOutputStream())); out.write(Msg, offset, length); out.flush(); break; } } 不知道問題出在哪 我在client讀檔那邊加一個count 最後會跑到800多 送出關檔的訊息 但是server端只會收到34X ..... 請問我有哪邊寫不好或是寫錯請各位大大指點 謝謝!! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 118.165.56.211

08/14 15:15, , 1F
我 java 忘的差不多了,不過我大概猜一下是哪裡錯誤
08/14 15:15, 1F

08/14 15:18, , 2F
你 client 開 byte array 2043 個,server 卻開 5000個
08/14 15:18, 2F

08/14 15:20, , 3F
5000*832 = 2043*340,應該是buf大小差異無誤!!!!!
08/14 15:20, 3F

08/14 17:25, , 4F
喔喔喔 有好多了耶!!! 但是最後還是會漏幾個...Q___Q
08/14 17:25, 4F
還是說...送過去的大小最好都一樣???? ※ 編輯: ohohyeah 來自: 118.165.56.253 (08/14 17:58)

08/14 19:43, , 5F
收一個封包就要 new 一次DataOutputStream啦
08/14 19:43, 5F

08/14 19:48, , 6F
為啥收一個要 new 一次? 不懂
08/14 19:48, 6F
挖喔可以了...太感謝了!!!! 阿....可不可以再問一下 為什麼我收到的檔案是0K 我有關檔阿Q__Q 多new一次是因為他本來是funtion 用來傳給連到這server的所有client 看來我該換寫法了 code如下 private static ArrayList<Socket> players=new ArrayList<Socket>(); .... Socket[] ps=new Socket[players.size()]; .... for (Socket socket :ps ) { try { out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream())); out.write(Msg, offset, length); out.flush(); Log.i("castMsg","castMsg : c = "+c); c++; } ※ 編輯: ohohyeah 來自: 118.165.56.253 (08/14 21:32) ※ 編輯: ohohyeah 來自: 118.165.56.253 (08/14 22:02) ※ 編輯: ohohyeah 來自: 118.165.56.253 (08/14 22:03)
文章代碼(AID): #1EHX8h61 (java)