📄 filesend.java
字号:
//文件发送
package dssclient;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.RandomAccessFile;
import java.net.Socket;
class filesend implements Runnable
{
String host;
private int acceptFlag = -1;
long lastFilePointer = 0;
long resumeSize = 0;
static DataInputStream input; //输入流
static DataOutputStream output; //输出流
static RandomAccessFile outFile; //访问的文件
static Socket socket;
public filesend(File toSend,String host)
{
this.host = host;
}
static void cancel() //关闭
{
try
{
outFile.close();
input.close();
output.flush();
output.close();
socket.close();
}
catch(Exception e)
{
FileSender.theApp.handleException(e.toString());
}
}
public void run()
{
try
{
socket = new Socket(host,Integer.parseInt(FileSender.theApp.portTextField.getText()));//主机和端口
FileSender.theApp.cancelButton.setEnabled(true);
input = new DataInputStream(socket.getInputStream());
output = new DataOutputStream(socket.getOutputStream());
output.writeLong(FileSender.MAGIC_NUMBER);
long fileSize = FileSender.theApp.toSend.length();
output.writeInt(FileSender.theApp.toSend.getName().length());
output.writeChars(FileSender.theApp.toSend.getName());
System.out.println(FileSender.theApp.toSend.getName());
output.writeLong(fileSize);
acceptFlag = input.readInt();
if(acceptFlag == 0) //保存不了
{
input.close();
output.close();
socket.close();
FileSender.theApp.otherSideCanceled();
FileSender.theApp.fileButton.setEnabled(true);
FileSender.theApp.sendButton.setEnabled(true);
return;
}
if(acceptFlag == 2) //恢复
{
resumeSize = input.readLong();
lastFilePointer = resumeSize;
acceptFlag = 1;
}
if(acceptFlag == 1) //传输
{
FileSender.theApp.pauseButton.setEnabled(true);
byte[] outBuf = new byte[FileSender.theApp.bufferSize];
int outBytesRead = 0;
outFile = new RandomAccessFile(FileSender.theApp.toSend,"r");
outFile.seek(resumeSize);
while((outBytesRead = outFile.read(outBuf))>-1)
{
if(FileSender.theApp.goOn.getGoOn() == false)
{
synchronized(FileSender.theApp.goOn)
{
FileSender.theApp.goOn.wait();
}
}
output.write(outBuf,0,outBytesRead);
}
input.close();
outFile.close();
output.flush();
output.close();
socket.close();
FileSender.theApp.pauseButton.setEnabled(false);
FileSender.theApp.fileButton.setEnabled(true);
FileSender.theApp.sendButton.setEnabled(true);
FileSender.theApp.cancelButton.setEnabled(false);
FileSender.theApp.fileSent();
}
}
catch(Exception e)
{
FileSender.theApp.handleException(e.toString());
}
finally
{
FileSender.theApp.pauseButton.setEnabled(false);
FileSender.theApp.fileButton.setEnabled(true);
FileSender.theApp.sendButton.setEnabled(true);
FileSender.theApp.cancelButton.setEnabled(false);
FileSender.theApp.goOn.setGoOn(true);
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -