TCP上传图片的例子
求救啊!大脑现在蒙圈了,编译正常,运行就挂了 大家帮忙看看代码怎么回事
- import java.io.*;
- import java.net.*;
- class TCPsoket11
- {
- public static void main(String[] args){
- Socket s = null;
- FileInputStream fis = null;
- try
- {
- s = new Socket("127.0.0.1",10245);
- fis = new FileInputStream("c\\1.jpg");
- OutputStream out= s.getOutputStream();
- int len = 0;
- byte[] but = new byte[1024];
- while ((len = fis.read(but))!=-1)
- {
- out.write(but,0,len);
- }
- s.shutdownOutput();
- BufferedReader bfr = new BufferedReader(new InputStreamReader(s.getInputStream()));
- String lin = bfr.readLine();
- System.out.println(lin);
- }
- catch (Exception e)
- {
- System.out.println(e);
- }
- finally
- {
- try{if(fis!=null) fis.close();}catch (Exception e){System.out.println(e);}
- try{if(s!=null) s.close();}catch (Exception e){System.out.println(e);}
- }
- }
- }
- class TCPSrever11 implements Runnable
- {
- private Socket ss;
- TCPSrever11(Socket ss){this.ss = ss;}
- public void run()
- {
- File file = new File("D:\\updata");
- if (!file.exists())
- file.mkdirs();
- String FileName = "itheima"+System.currentTimeMillis()+".jpg";
- File updata = new File(file,FileName);
- FileOutputStream fos = null;
- try
- {
- fos = new FileOutputStream(updata);
- InputStream in = ss.getInputStream();
- int len = 0;
- byte[] but = new byte[1024];
- while((len = in.read(but))!=-1)
- {
- fos.write(but,0,len);
- }
- OutputStream out = ss.getOutputStream();
- out.write("上传成功".getBytes());
- }
- catch (Exception e)
- {
- System.out.println(e);
- }
- finally
- {
- try{if(fos!=null)fos.close();}catch (Exception e){System.out.println(e);}
- try{if(ss!=null)ss.close();}catch (Exception e){System.out.println(e);}
- }
-
- }
- }
- class TCPSocketSrever1
- {
- public static void main(String[] args) throws Exception
- {
- ServerSocket ss = new ServerSocket(10000);
- while (true)
- {
- Socket s = ss.accept();
- new Thread(new TCPSrever11(s)).start();
- }
- }
- }
复制代码
|