import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.Date;
public class FileSocket {
private Socket clientSocket;
private InetSocketAddress tcpAddress;
private OutputStream out;
private FileInputStream fin;
private FileOutputStream fout;
private PrintWriter PW;
private InputStream in;
// private Date sendTime;
private final int receiveMaxSize = 1024 * 1024; // 设置一次接收数据的大小, 如果不设置,默认为1M
private final int BUFFSIZE=1024*1024;
//客户端唯一标识号码, 类似于HTTP的Session
public FileSocket(String ip, int port)
{
tcpAddress = new InetSocketAddress(ip,port);
}
public boolean isConnected()
{
return clientSocket.isConnected();
}
/**
* 对服务端口的连接
* @return true成功, false表示失败
*/
public boolean connect()
{
try
{
if(clientSocket != null && clientSocket.isConnected())
{
out.close();
in.close();
clientSocket.close();
clientSocket = null;
}
clientSocket = new Socket();
clientSocket.connect(tcpAddress);
if( clientSocket.isConnected() )
{
out = clientSocket.getOutputStream();
in = clientSocket.getInputStream();
return true;
}
}
catch(IOException ex)
{
}
clientSocket = null;
out = null;
in = null;
return false;
}
/**
* 发送特定编码的String到服务端
* @param sendString
* @param charset 指定的编码
* @throws Exception
*/
public void Send(String sendString, String charset) throws Exception
{
byte[] datas = sendString.getBytes(charset);
Send(datas);
}
private void SendFile(String filepath) throws IOException {
fin = new FileInputStream(filepath);
byte buffer[] = new byte[BUFFSIZE];
int temp = 0;
// 循环读取文件
while ((temp = fin.read(buffer)) != -1) {
// 把数据写入到OuputStream对象中
out.write(buffer, 0, temp);
}
// 发送读取的数据到服务端
out.flush();
}
public void Send(byte[] datas) throws Exception
{
if( null == clientSocket || clientSocket.isClosed())
{
throw new Exception("socket closed!");
}
out.write(datas);
out.flush();
}
public byte[] Receive(int length)throws Exception
{
if( null == clientSocket || clientSocket.isClosed())
{
throw new Exception("socket closed!");
}
byte []buffer=new byte[length];
in.read(buffer);
return buffer;
}
public void Close()
{
try {
clientSocket.close();
in.close();
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 比较特殊的接收方式, 比如按照状态机的接收方式, 需要将该接口暴露在外面, 留给外部较大的自由度
* 原因是大部分数据接收是分批次, 并且有结束标示
* @return
*/
public InputStream getInputStream()
{
return in;
}
public OutputStream getOutputStream()
{
return out;
}
}