日期:2014-05-20 浏览次数:21012 次
//客户端
public class CompressClient
{
public static final int BUFSIZE = 256;
public static void main(String[] args) throws IOException
{
InetAddress inetAddr = InetAddress.getLocalHost();
int port = 8888;
String fileName = "D:\\杂乱\\桌面.jpg";
FileOutputStream fileOut = new FileOutputStream(fileName + ".gz");
final FileInputStream fileIn = new FileInputStream(new File(fileName));
final Socket sock = new Socket(inetAddr, port);
// 情况一:不会出现阻塞
// Thread thread = new Thread()
// {
// @Override
// public void run()
// {
// try
// {
// sendBytes(sock, fileIn);
// }
// catch (IOException e)
// {
// e.printStackTrace();
// }
// }
// };
// thread.start();
// 情况二:会出现阻塞
sendBytes(sock, fileIn);
// 接收压缩服务器信息
InputStream sockIn = sock.getInputStream();
int bytesRead;
byte[] buffer = new byte[BUFSIZE];
while ((bytesRead = sockIn.read(buffer)) != -1)
{
fileOut.write(buffer, 0, bytesRead);
System.out.print("R");
}
System.out.println();
fileIn.close();
fileOut.close();
sock.close();
}
private static void sendBytes(Socket socket, InputStream fileIn)
throws IOException
{
OutputStream sockOut = socket.getOutputStream();
int bytesRead = 0;
byte[] buffer = new byte[BUFSIZE];
while ((bytesRead = fileIn.read(buffer)) != -1)
{
sockOut.write(buffer, 0, bytesRead);
System.out.print("W");
}
System.out.println("\nClient send data complete!");
socket.shutdownOutput();
System.out.println("Client is deadlock? No");
}
}
//服务端
public class TCPEchoServerExecutor
{
public static void main(String[] args) throws IOException
{
int echoServProt = 8888;
ServerSocket servSock = new ServerSocket(echoServProt);
Logger logger = Logger.getLogger("practical");
Executor service = Executors.newCachedThreadPool();
while (true)