package day1;
import jdk.internal.util.xml.impl.Input;
import org.junit.Test;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class TCPdemo2 {
//从客户端发送文件到服务器端,服务器端保存并返回“发送成功”并关闭连接
@Test
public void server() throws IOException {
ServerSocket ss=new ServerSocket(9090);
Socket socket=ss.accept();
InputStream is=socket.getInputStream();
//接收文件并保存
FileOutputStream fos=new FileOutputStream(new File("der2.jpg"));
byte[] buf=new byte[30];
int len;
while((len=is.read(buf))!=-1){
fos.write(buf,0,len);
}
OutputStream os=socket.getOutputStream();
os.write("服务器端接收图片成功".getBytes());
fos.close();
is.close();
socket.close();
ss.close();
os.close();
}
@Test
public void client() throws IOException {
Socket socket=new Socket("127.0.0.1",9090);
OutputStream os=socket.getOutputStream();
FileInputStream fis=new FileInputStream(new File("der.jpg"));
byte[] buf=new byte[30];
int len;
while((len=fis.read(buf))!=-1){
os.write(buf,0,len);
}
//结束输出,避免server阻塞
socket.shutdownOutput();
InputStream is=socket.getInputStream();
ByteArrayOutputStream baos=new ByteArrayOutputStream();
byte[] buf1=new byte[20];
int len1;
while((len1=is.read(buf1))!=-1){
baos.write(buf1,0,len1);
}
System.out.println(baos.toString());
fis.close();
os.close();
socket.close();
baos.close();
}
}
标签:socket,TCPdemo2,len,close,new,byte,buf From: https://www.cnblogs.com/fighterk/p/16933503.html