将接收到的图片保存到相对地址
在这里客户端要发送一个图片给服务端,那么客户端就必须得先读入自己有的图片,所以需要输入流。
服务器端需要把图片保存起来,所以需要加个输出流。
public class TCPSave {
@Test
public void Client(){
FileInputStream fis= null;
OutputStream os= null;
try {
//指明端口号和ip
InetAddress ia=InetAddress.getByName("127.0.0.1");
Socket socket=new Socket(ia,4567);
//流
fis = new FileInputStream(new File("123.jpg"));
os = socket.getOutputStream();
int len;
byte[] buf=new byte[1024];
while((len=fis.read(buf))!=-1){
os.write(buf,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fis!=null){
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(os!=null){
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
;
}
}
}
@Test
public void Server(){
ServerSocket serverSocket = null;
Socket socket= null;
InputStream is= null;
FileOutputStream fos= null;
try {
//端口号
serverSocket = new ServerSocket(4567);
//等待连接
socket = serverSocket.accept();
//流的接收
is = socket.getInputStream();
fos = new FileOutputStream("456.jpg");
int len;
byte[] bytes=new byte[1024];
while((len=is.read(bytes))!=-1){
fos.write(bytes,0,len);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if(serverSocket!=null){
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(is!=null){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(fos!=null){
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}