tcpServer端代码
- public class DoServer implements Runnable{
- private Socket socket ;
- DoServer(Socket socket ){
- this.socket = socket;
- }
- @Override
- public void run() {
- copyFileServer();
- }
- public void copyFileServer(){
- BufferedOutputStream socOut = null;
- BufferedInputStream socIn = null;
-
- BufferedOutputStream fileOut = null;
- try {
- String ip =socket.getInetAddress().getHostAddress();
- socIn =new BufferedInputStream(socket.getInputStream());
- socOut = new BufferedOutputStream(socket.getOutputStream());
- String path = "E:"+File.separator+"test"+File.separator+"temp"+File.separator;
- ///通过 流 和默认地址,得到要存放的文件
- File file = getSaveFile(socIn,path);
- System.out.println(ip+"-----------"+file);
- fileOut = new BufferedOutputStream(new FileOutputStream(file));
- byte [] buf =new byte[1024];
- int len = -1;
- while(( len = socIn.read(buf))!=-1){
- fileOut.write(buf,0,len);
- fileOut.flush();
- }
- socket.shutdownInput();
- System.out.println("------------服务器端已经把数据全部写入到指定文件中"+file+"---------");
- socOut.write("已经上传完毕".getBytes());
- socOut.flush();
- fileOut.close();
- socket.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- /**
- * 通过 socket获取流对象,然后根据流对象获取 客户端发送的要上传的文件名称
- * @param in
- * @param path
- * @return
- * @throws IOException
- */
- public static File getSaveFile(InputStream in,String path) throws IOException{
- int count =1;
- //这里不知道客户端上传的文件 名称是多少字符的,我就定义了 差不多 100个字符的长度
- byte []bufName = new byte[200];
- /*这里获取 客户端发送的文件名称,可能会把文件内容也获取到,这样的话就不是文件的名称了 ,所以服务器会报错 */
- int l = in.read(bufName);
- String fileName = new String(bufName,0,l);
- // String fileName ="test.png";
- String sufName = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
- String preName = fileName.substring(0, fileName.lastIndexOf("."));
- File file = new File(path+preName+"("+count+")"+"."+sufName);
- while(file.exists()){
- file = new File(path+preName+"("+count++ +")"+"."+sufName);
- }
- return file;
- }
- }
复制代码 |