本帖最后由 nestor 于 2014-4-12 17:10 编辑
服务端:
- package NetDemo;
- import java.net.*;
- import java.io.*;
- class PicThread implements Runnable{
- private Socket s;
- PicThread(Socket s) {
- this.s=s;
- }
- @Override
- public void run() {
- int count = 0;
- String ip=s.getInetAddress().getHostAddress();
- try {
- System.out.println(ip+":connected");
- InputStream in =s.getInputStream();
-
- File file =new File("E:\\Demo\\"+ip+"("+(count++)+").jpg");
- while (file.exists()) {
- file =new File("E:\\Demo\\"+ip+"("+(count++)+").jpg");
- }
-
- FileOutputStream fos=new FileOutputStream(file);
-
- byte[] buf=new byte[1024];
-
- int len=0;
- while ((len=in.read(buf))!=-1) {
- fos.write(buf, 0, len);
- }
-
- OutputStream out=s.getOutputStream();
-
- out.write("上传成功".getBytes());
-
- fos.close();
- s.close();
- } catch (Exception e) {
- throw new RuntimeException(ip+"上传失败");
- }
-
- }
- }
- class PicServer{
- public static void main(String[] args) throws Exception{
- ServerSocket ss=new ServerSocket(10005);
- while (true) {
- Socket s=ss.accept();
-
- new Thread(new PicThread(s)).start();
- }
- }
- }
复制代码
客户端:
- package NetDemo;
- import java.net.*;
- import java.io.*;
- class PicClient {
- public static void main(String[] args) throws Exception {
- Socket s=new Socket("127.0.0.1",10005);
-
- FileInputStream fis=new FileInputStream("E:\\Demo\\in.pic");
-
- OutputStream out=s.getOutputStream();
-
- byte[] buf=new byte[1024];
- int len=0;
- while ((len=fis.read(buf))!=-1) {
- out.write(buf, 0, len);
- }
-
- s.shutdownOutput();
-
- InputStream in=s.getInputStream();
- byte[] bufin=new byte[1024];
- int num=in.read(bufin);
- System.out.println(new String(bufin,0,num));
-
- fis.close();
- s.close();
- }
- }
复制代码
报错:
- 127.0.0.1:connected
- Exception in thread "Thread-0" java.lang.RuntimeException: 127.0.0.1上传失败
- at NetDemo.PicThread.run(PicServer.java:35)
- at java.lang.Thread.run(Thread.java:744)
复制代码
看了几遍还是找不到原因啊:'(
|