2013年12月15日星期日

Small exercises socket transmission of the picture, a little mistake Great God help look . .

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

public class PicClient {
public static void main(String[] args) {
try {

Socket s = new Socket("localhost", 10007);
FileInputStream fis = new FileInputStream("E:\\壁纸\\05.jpg");
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = s.getOutputStream();

byte bf[] = new byte[1024];
int len = 0;

while ((len = bis.read(bf)) != -1) {
os.write(bf, 0, len);
}
s.shutdownOutput();

BufferedInputStream back = new BufferedInputStream(s.getInputStream());
byte[] bk = new byte[1024];
int lb = back.read(bk) ;

System.out.println(new String(bk, 0, lb));

bis.close();
s.close();

} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

client code above :
see tutorial is so written , found only 27 lines running lb = -1; so line 29 will appear subscript out of range ,

But I want to remove all significant byte stored inside the bk do not know what , but to achieve

seek advice. . .

server-side code is as follows :

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class PicServer {
public static void main(String[] args){
try {
ServerSocket ss=new ServerSocket(10007);
Socket s=ss.accept();

String ip=s.getInetAddress().getHostAddress();
System.out.print(ip);

InputStream is=s.getInputStream();
BufferedInputStream bis=new BufferedInputStream(is);

FileOutputStream fos=new FileOutputStream("E:\\05.jpg");
BufferedOutputStream bos=new BufferedOutputStream(fos);

byte[] bt=new byte[1024];
int len=0;
while((len=bis.read(bt))!=-1){
bos.write(bt, 0, len);
}

BufferedOutputStream bac=new BufferedOutputStream(s.getOutputStream());

bac.write("图片传送成功!".getBytes());

bos.close();
ss.close();
s.close();

} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}
}

------ Solution ------------------------------------- -------
Client -side
			byte[] bk=new byte[1024];
int lb=0;
int i;
while((i=back.read())!=-1){
lb++;
}
System.out.println(lb);
System.out.println(new String(bk,0,lb));


Server side BufferedOutputStream finish, coupled with close method .

your problem solved, but the code does not solve the problem . . . .
------ For reference only -------------------------------------- -



byte[] bk = new byte[1024];
int lb = 0;
while ((lb = back.read(bk)) != -1)
System.out.println(new String(bk, 0, lb));


directly like this , do not return information before tried to write that this is wrong, ,

After a while I found your bac remind the stream is not closed , resulting did not write out

Thank

没有评论:

发表评论