java模拟TCP通信--实现客户端上传文件到服务器端,文件上传到服务端可以打开但字节为零没有内容
客户端
public class TCPCclient {
public static void main(String[] args) throws IOException{
FileInputStream fis = new FileInputStream("D:\\暑假\\123\\无标题.png");
Socket socket = new Socket("127.0.0.1",8882);
OutputStream os = socket.getOutputStream();
//while(fi)
byte[] bytes= new byte[1024];
int len=0;
while((len= fis.read(bytes))!=-1){
os.write(bytes,0,len);
}
socket.shutdownOutput();
//System.out.println("55555555555");
InputStream is = socket.getInputStream();
while ((len=is.read(bytes))!=-1){
System.out.println(new String(bytes,0,len));
}
fis.close();
socket.close();
}
}
服务端
public class TCPServlet {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(8882);
while (true) {
Socket socket = server.accept();
new Thread(new Runnable() {
@Override
public void run() {
try {
InputStream is = socket.getInputStream();
File file = new File("d:\\upload");
if (!file.exists()) {
file.mkdir();
}
String fileName = "itcast" + System.currentTimeMillis() + new Random(9999);
FileOutputStream fos = new FileOutputStream(file+"\\"+fileName);
int len = 0;
//System.out.println("111111111111");
byte[] bytes = new byte[1024];
while ((is.read(bytes)) != -1) {
fos.write(bytes, 0, len);
}
//System.out.println("3333333333333");
socket.getOutputStream().write("上传成功".getBytes(StandardCharsets.UTF_8));
fos.close();
socket.close();
} catch (IOException e) {
System.out.println(e);
}
}
}).start();
}
}
}