这里主要描述了客户端把未压缩的文件通过客户端发送到服务器,服务器把它压缩后再返回给客户端。在Socket中有shutdownOutput与shutdownInput方法,关闭输入输出流,互不影响。这里当客户端把未压缩的文件传输完毕后,通过关闭Socket 的shutdownOutput方法,并不影响从服务器返回的压缩的数据的接收。(这里只能处理小文件)大文件,后面学会了再继续整理出来。
//客户端
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class CompressClient {
private static String IP = "10.108.1.43";
private static int PORT = 4444;
//未压缩数据的路径
private static String PATH = "/Users/hyw/Downloads/xxx.jpeg";
private static int BUFFERSIZE = 256;
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream(PATH);
FileOutputStream out = new FileOutputStream(PATH+".gz");
Socket socket = new Socket(IP, PORT);
sendBytes(in,socket);
receiveBytes(out,socket);
in.close();
out.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//接收从服务器返回的压缩数据
private static void receiveBytes(FileOutputStream out, Socket socket) throws IOException {
InputStream in = socket.getInputStream();
int bytes;
byte buffer[] = new byte[BUFFERSIZE];
while((bytes = in.read(buffer))!= -1)
{
out.write(buffer, 0, bytes);
System.out.println("R");
}
}
//把没有压缩的数据传输到服务器
private static void sendBytes(FileInputStream in, Socket socket) throws IOException {
OutputStream out = socket.getOutputStream();
int byteRead;
byte []buffer = new byte[BUFFERSIZE];
while((byteRead = in.read(buffer)) != -1)
{
out.write(buffer, 0, byteRead);
//out.flush();
System.out.println("w");
}
//未压缩的数据发送完后,客户端输出到服务端的操作关闭,
//但是不影响继续接收从服务端发过来的数据
socket.shutdownOutput();
System.out.println("finish");
}
}
//服务器
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class CompressServer {
public static void main(String[] args) {
try {
ServerSocket server = new ServerSocket(4444);
Socket socket = null;
while(true){
socket = server.accept();
System.out.println("connect");
new Thread(new CompressProtol(socket)).start();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.zip.GZIPOutputStream;
//服务器压缩协议,并且把压缩完的数据传回客户端
public class CompressProtol implements Runnable{
private static final int BUFFERSIZE = 1024;
private Socket mSocket;
public CompressProtol(Socket s) {
this.mSocket = s;
}
@Override
public void run() {
handleCompressHandler(mSocket);
}
public static void handleCompressHandler(Socket s)
{
try {
InputStream in = s.getInputStream();
GZIPOutputStream gOut = new GZIPOutputStream(s.getOutputStream());
int byteRead;
byte buffer[] = new byte[BUFFERSIZE];
while((byteRead = in.read(buffer)) != -1){
gOut.write(buffer, 0, byteRead);
gOut.flush();
}
gOut.finish();
s.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}