Java代码
/*服务器端接收文件*/
importjava.io.File;
importjava.io.IOException;
importjava.io.InputStream;
importjava.io.RandomAccessFile;
importjava.net.ServerSocket;
importjava.net.Socket;
importjavax.swing.JFileChooser;
/**
* 该类用到的绑定端口初始为10000,如果绑定不成功则试另外的端口;
* 绑定次数用tryBindTimes变量,表示如果绑定失败会对它加一;
* 当前绑定端口由DefaultBindPort+tryBindTimes决定;
* 外界系统(调用此程序的对象)可以获取当前的帮定端口;
* 并告诉客户端服务的端口号以使其能正确连接到该端口上;
* @author
*
*/
publicclassGetFileextendsThread {
// 服务套接字等待对方的连接和文件发送
ServerSocket serSocket;
// 由服务套接字产生的 套接字
Socket tempSocket;
// 用于读取
InputStream inSocket;
// 随机访问文件
RandomAccessFile inFile = null;
// 临时缓寸区
bytebyteBuffer[] =newbyte[1024];
// 默认用10000端口监听请求
intdefaultBindPort =10000;
// 初始的绑定端口次数为0
inttryBindTimes =0;
// 当前绑定的端口号是10000默认端口
intcurrentBindPort = defaultBindPort + tryBindTimes;
/**
* @构造方法
* @抛出异常的原因是无法绑定服务的端口
* */
publicGetFile(intport)throwsException {
try{
// 绑定服务的端口
this.bindToServerPort();
} catch(Exception e) {
e.printStackTrace();
// 绑定不成功重试
System.out.println(e.toString());
thrownewException("绑定端口不成功!");
}
// 文件选择器以当前的目录打开
JFileChooser jfc = newJFileChooser(".");
jfc.showSaveDialog(newjavax.swing.JFrame());
// 获取当前的选择文件引用
File savedFile = jfc.getSelectedFile();
// 已经选择了文件
if(savedFile !=null) {
// 读取文件的数据,可以每次以快的方式读取数据
inFile = newRandomAccessFile(savedFile,"rw");
}
}
/**
* @监控线程
*/
publicvoidrun() {
try{
if(this.inFile ==null) {
System.out.println("没有选择文件");
// 关闭服务方套接字
this.serSocket.close();
// 没有选择文件
return;
}
System.out.println("wait for..."+'\n'+"等待对方接入");
// 等待对方的连接</