package cn.itcast_14;
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;
/*
* 通过while循环可以改进一个服务器接收多个客户端。
* 但是这个是有问题的。
* 如果是这种情况,假设我还有张三,李四,王五这三个分别执行客户端
* 张三:好好学习.avi(100M) 256k
* 李四:天天赂上.mp3(3M) 1M
* 王五:ILoveJava.txt(1k) 100M
*/
public class UploadServer {
public static void main(String[] args) throws IOException {
// 创建服务器Socket对象
ServerSocket ss = new ServerSocket(45678);
while (true) {
// 监听客户端链接
Socket s = ss.accept();
// 封装通道内流
BufferedInputStream bis = new BufferedInputStream(
s.getInputStream());
// 封装图片文件
BufferedOutputStream bos = new BufferedOutputStream(
new FileOutputStream("a.jpg"));
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();
}
}
}
package cn.itcast_14;
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("127.0.0.1", 45678);
// 封装图片文件
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(
"林青霞.jpg"));
// 封装通道内数据
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();
}
}