[問題] socket 漏接??
各位好!
小弟想用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
08/14 15:15, 1F
→
08/14 15:18, , 2F
08/14 15:18, 2F
→
08/14 15:20, , 3F
08/14 15:20, 3F
→
08/14 17:25, , 4F
08/14 17:25, 4F
還是說...送過去的大小最好都一樣????
※ 編輯: ohohyeah 來自: 118.165.56.253 (08/14 17:58)
推
08/14 19:43, , 5F
08/14 19:43, 5F
→
08/14 19:48, , 6F
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)