日期:2014-05-20 浏览次数:20860 次
package 智能识别系统客户端;
import java.io.*;
import java.net.Socket;
public class Client
{
//将int类型转换成字节
public static byte[] i2b(int i)
{
return new byte[]
{
(byte) (i & 0xFF),
(byte) ((i >> 8) & 0xFF),
(byte) ((i >> 16) & 0xFF),
(byte) ((i >> 24) & 0xFF),
};
}
//将字节转换成int类型
public static int b2i(byte[] b)
{
return b[0] & 0xff | (b[1] & 0xff) << 8 | (b[2] & 0xff) << 16 | (b[3] & 0xff) << 24;
}
/**
* 发送和接收文件。文件大小不能大于 {@link Integer#MAX_VALUE}
*
* @param hostname 接收端主机名或 IP 地址
* @param port 接收端端口号
* @param filepath 要发送的文件路径
* @param recfilepath 接收的文件路径
*
* @throws IOException 如果读取文件或发送失败
*/
public void TransportFile(String hostname,int port,String filepath,String recfilepath) throws IOException
{
Socket ConnectSocket = new Socket(hostname,port); //与服务器建立连接
File file = new File(filepath); //打开要发送的文件
FileInputStream fis = new FileInputStream(filepath); //文件输入流
OutputStream os = ConnectSocket.getOutputStream(); //socket输出流
//File recfile = new File(recfilepath); //打开或新建要接收的文件
InputStream is = ConnectSocket.getInputStream(); //socket输入流
FileOutputStream fos = new FileOutputStream(recfilepath); //文件输出流
writeFileLength(file,os); //发送文件大小
writeFileContent(fis,os); //发送文件
int length;
length = readFileLength(is); //接收文件大小
readFileContent(is,fos,length); //接收文件
os.close();
fis.close();
is.close();
fos.close();
ConnectSocket.close(); //关闭套接字
}
//输出文件大小
private void writeFileLength(File file,OutputStream os) throws IOException
{
os.write(i2b((int)file.length()));
}
//输出文件
private void writeFileContent(InputStream is,OutputStream os) throws IOException
{
byte[] buffer = new byte[30];
int size = 0;
while((size=is.read(buffer)) != -1)
{
os.write(buffer,0,size);
}
}
//接收文件大小
private int readFileLength(InputStream is) throws IOException
{
byte[] l = new byte[4];
while(is.available()>0)
{
is.read(l);
break;
}
return b2i(l);
}
//接收文件
private void readFileContent(InputStream is,OutputStream os,int length) throws IOException
{
byte[] buffer = new byte[30];
int size = 0;
int count=0;
/*while((size=is.read(buffer)) != -1)
{
os.write(buffer,0,size);
}*/
while(is.available()>0)
{
size = is.read(buffer);
os.write(buffer,0,size);
os.flush();
count += size;
if(count>=length)
break;
}
}
//主函数
public static void main(String[] args) throws IOException
{
new Client().TransportFile("127.0.0.1",8889,"F://test.jpg","F://client_rec.jpg");
}
}