- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- * 9、 使用TCP协议写一个可以上传文件的服务器和客户端。
- *
- * @author 刘阳文
- * */
- public class Test9
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(8888);
- while(true)
- {
- Socket socket = ss.accept();
- new Thread(new TcpServer(socket)).start();
- }
- }
- }
复制代码
- import java.io.BufferedInputStream;
- import java.io.File;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.io.OutputStream;
- import java.net.Socket;
- /**
- * Tcp文件上传 服务端
- *
- * @author 刘阳文
- * */
- public class TcpServer implements Runnable
- {
- private Socket socket;
- public TcpServer(Socket socket)
- {
- this.socket = socket;
- }
- public void run()
- {
- OutputStream outputStream = null;
- try
- {
- InputStream inputStream = socket.getInputStream();
- BufferedInputStream bis = new BufferedInputStream(inputStream);
- bis.mark(0);
- byte[] buf = new byte[1024];
- int len = 0;
- len = bis.read(buf);
- String str = new String(buf,0,len);
- String[] strs = str.split("----");
- bis.reset();
- bis.skip((strs[0].length()+"----".length())+(int)8);
- String[] fileNames = strs[0].substring(strs[0].lastIndexOf(File.separatorChar)+1).split("\\.");
- int count = 0;
- String fileName = fileNames[0]+"("+(++count)+")."+fileNames[1];
- File file = new File(fileName);
- if(file.exists())
- file = new File(fileName);
- outputStream = new FileOutputStream(file);
- while((len = bis.read(buf)) > 0)
- {
- outputStream.write(buf, 0, len);
- }
-
- } catch (IOException e)
- {
- e.printStackTrace();
- }
- finally
- {
- try
- {
- if(outputStream != null)
- outputStream.close();
- } catch (Exception e2)
- {
- System.out.println("文件写入流关闭异常");
- }
- try
- {
- if(socket != null)
- socket.close();
- } catch (Exception e2)
- {
- System.out.println("socket关闭异常");
- }
- }
-
- }
- }
复制代码 |
|