A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 弗人 中级黑马   /  2015-10-10 15:24  /  521 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

客户端代码:
package cn.itcast_13;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class UploadClient {
public static void main(String[] args) throws IOException {
  // 创建客户端Socket对象
  Socket s = new Socket("192.168.15.63", 19191);
  // 封装图片文件
  BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
    "b.png"));
  // 封装通道内的流
  BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
  byte[] bys = new byte[1024];
  int len = 0;
  while ((len = bis.read(bys)) != -1) {
   bos.write(bys, 0, len);
   bos.flush();
  }
  
  s.shutdownOutput();
  // 读取反馈
  InputStream is = s.getInputStream();
  byte[] bys2 = new byte[1024];
  int len2 = is.read(bys2);
  String client = new String(bys2, 0, len2);
  System.out.println(client);
  // 释放资源
  bis.close();
  s.close();
}
}


客户端代码为:
package cn.itcast_13;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class UploadServer {
public static void main(String[] args) throws IOException {
  // 创建服务器Socket对象
  ServerSocket ss = new ServerSocket(19191);
  // 监听客户端连接
  Socket s = ss.accept();
  // 封装通道内流
  BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
  // 封装图片文件
  BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream("科目四报名.png"));
  byte[] bys = new byte[1024];
  int len = 0;
  while ((len = bis.read(bys)) != -1) {
   bos.write(bys, 0, len);
   bos.flush();
  }
  // 给一个反馈
  OutputStream os = s.getOutputStream();
  os.write("图片上传成功".getBytes());
  bos.close();
  s.close();
}
}

代码和上课的老师代码一样的,但是为什么会报这个错呢?
Exception in thread "main" java.net.ConnectException: Connection timed out: connect

3 个回复

倒序浏览
你需要先运行服务Server 程序
再运行client 去链接
回复 使用道具 举报
徐慧shanghai 发表于 2015-10-10 16:17
你需要先运行服务Server 程序
再运行client 去链接

我是这样操作的额,关键是第一次成功了,再后面就这样了{:3_52:}
回复 使用道具 举报
弗人 发表于 2015-10-10 17:54
我是这样操作的额,关键是第一次成功了,再后面就这样了

public static void main(String[] args) throws IOException {
  // 创建服务器Socket对象
  ServerSocket ss = new ServerSocket(19191);
  // 监听客户端连接
  Socket s = ss.accept();
  // 封装通道内流
  BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
  // 封装图片文件
  BufferedOutputStream bos = new BufferedOutputStream(
    new FileOutputStream("科目四报名.png"));
  byte[] bys = new byte[1024];
  int len = 0;
  while ((len = bis.read(bys)) != -1) {
   bos.write(bys, 0, len);
   bos.flush();
  }
  // 给一个反馈
  OutputStream os = s.getOutputStream();
  os.write("图片上传成功".getBytes());
  bos.close();
  s.close();
}
}

你看一下你的服务端的程序
成功了一次之后就会关闭socket,所以服务器就关闭了,第二次自然就失败了
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马