📄 filesendthread.java
字号:
package XXRoom;
import java.net.*;
import java.io.*;
//发送文件的线程, 当文件接收完毕发送一个标志位
class FileSendThread extends Thread implements FileThread
{
Client client;
ServerSocket sSkt;
String filePath;
FileInputStream fis;
Socket skt;
OutputStream write;
String name;//要发送的用户的名字
public FileSendThread ( Client client , String filePath , String name )
{
this.client = client;
this.filePath = filePath;
this.name = name;
client.isFileTrans = true;
client.file.setEnabled( false );
client.cancel.setEnabled( true );
client.fileCondition.setText( "等待接收..." );
int i = 1000;
//寻找可用端口
while( true ) {
try
{
sSkt = new ServerSocket( i );
break;
}
catch ( IOException e )
{
i++;
continue;
}
}
}
public void run()
{
try
{
skt = sSkt.accept();
write = skt.getOutputStream();
}
catch ( IOException e )
{
client.appendPersonalSystemMsg( "连接发生网络错误" );
dispose();
return;
}
//传送文件
try
{
client.fileCondition.setText( "正在传送文件 " + new File( filePath ).getName() );
fis = new FileInputStream( filePath );
byte buffer[] = new byte[ 1024 ];
while( fis.read( buffer ) != -1 ) {
write.write( buffer );
}
write.close();
fis.close();
skt.close();
sSkt.close();
}
catch ( FileNotFoundException e )
{
client.appendPersonalSystemMsg ( "找不到要传送的文件" + filePath );
dispose();
return;
}
catch ( IOException e )
{
client.appendPersonalSystemMsg ( "传送文件发生IO异常或对方取消了文件传送" );
dispose();
return;
}
// JOptionPane.showMessageDialog( client, "文件发送完毕" );
dispose();
}
public void dispose() {
client.isFileTrans = false;
client.file.setEnabled( true );
client.cancel.setEnabled( false );
client.fileCondition.setText( "" );
try
{
if( write != null )
write.close();
if( fis != null )
fis.close();
if( skt != null )
skt.close();
if( sSkt != null )
sSkt.close();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -