现在的位置: 首页 > 综合 > 正文

【无浪】用Socket类实现网络传输文件软件

2017年02月03日 ⁄ 综合 ⁄ 共 26520字 ⁄ 字号 评论关闭

Socket server=new ServerSocket(port).accept();    ————————————————     Socket client=new Socket(ip,port);

DataInputStream in=new DataInputStream(server.getInputStream);                              DataOutputStream out=new DataOutputStream(client.getInputStream);

DataOutputStream out=new DataOutputStream(server.getInputStream);
                    
 DataInputStream in=new DataInputStream(client.getInputStream);

out.writeXXX(XXX) ;                                                                                           →            in.readXXX(XXX);

in.readXXX(XXX);                                                                          
        out.writeXXX(XXX) ;


文件传输窗口菜单栏:

“操作菜单栏”

1.显示端口

2.发送文件

3.发起聊天

4.设置连接指向

5.显示IP地址



打开第一个网络传输软件

设置这台电脑的端口号

输入对方电脑的端口号

打开第二个网络传输软件,重复以上步骤

然后有两个传输软件

如果要连接其它电脑则让对方点击显示IP地址然后把IP地址告诉这边,然后点击设置连接指向设置对方的IP地址即可。

重新设置回本机

其中一个点击发送文件

弹出选择文件窗口

选择文件后

点击发送按钮

选择是,弹框选择保存路径

传送中…

传送完成

点击打开文件所在的位置按钮 

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Date;
import javax.swing.*;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.filechooser.FileSystemView;

public class FileTransfer {
    public static void main(String args[]){
        javax.swing.SwingUtilities.invokeLater(new Runnable(){
            public void run(){
                new ViewOfFileTransfer();
			}//run
		});
	}//main
}//FileTransfer


class Accept_Communication extends Thread implements ActionListener, WindowListener{
    private JFrame frame;
    private DataInputStream in;
    private DataOutputStream out;
    private JTextField InputText;
    private JTextArea OutputText;
    private boolean isOpening;
    Accept_Communication(Socket client) throws IOException{
		//构造网络输入输出流
        in=new DataInputStream(client.getInputStream());
        out=new DataOutputStream(client.getOutputStream());
        System.out.println("向对方发送true");
        out.writeBoolean(true);
        setFrame();
        isOpening=true;
        start();
	}
	public void setFrame(){
		//创建并设置窗体
				frame=new JFrame("聊天工具");
				//添加WindowListener事件
				frame.addWindowListener(this);
				//创建并设置菜单栏
				JMenuBar menubar=new JMenuBar();
				//创建并设置菜单"文件"
				JMenu menu=new JMenu("操作");
				//创建并设置子菜单"关闭"
				JMenuItem Close=new JMenuItem("关闭");	
				//创建输入框
				InputText=new JTextField();
				//创建聊天框
				OutputText=new JTextArea();
				//设置聊天框滚动条
				JScrollPane RollPane=new JScrollPane(OutputText);
				//聊天框设置不可修改
				OutputText.setEditable(false);
				//设置聊天框大小
				RollPane.setPreferredSize(new Dimension(250,100));
				//聊天框设置自动换行
				OutputText.setLineWrap(true);
				
				//窗体关闭时退出程序
				frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);		
				//设置窗口大小
				frame.setSize(500,400);
				//设置窗口位置
				frame.setLocation(250,250);
				//是否可见
				frame.setVisible(true);
				//是否可改变大小
				frame.setResizable(true);
				//显示窗体
				frame.setVisible(true);
				
				
				//窗体添加菜单栏,菜单栏放在窗体北侧
                frame.add(menubar,BorderLayout.NORTH);
				//窗体添加输入框,输入框放在窗体南侧
                frame.add(InputText,BorderLayout.SOUTH);
				//窗体添加聊天框滚动条(包含聊天框)
                frame.add(RollPane,BorderLayout.CENTER);
				//菜单栏添加菜单"关闭"
                menubar.add(menu);
				//菜单"操作"添加子菜单"关闭"
                menu.add(Close);
                Close.addActionListener(this);
                InputText.addActionListener(new ActionListener(){
                    public void actionPerformed(ActionEvent e) {
                        try {
                            Date nowTime=new Date();//时间类
                            OutputText.append(nowTime.toString()+"\r\nMe:"+InputText.getText()+"\r\n");
                            out.writeUTF(nowTime.toString()+"\r\nHim/Her:"+InputText.getText()+"\r\n");
                            OutputText.setSelectionStart(OutputText.getText().length());
                            OutputText.setSelectionEnd(OutputText.getText().length());
                            InputText.setText(null);
						} catch (IOException e1) {}
					}
				});
	}//setframe
	public void run(){
		System.out.println("接收方显示窗口");
		frame.setVisible(true);
		while(true){
			try {
				String Information=in.readUTF();
				OutputText.append(Information);
				OutputText.setSelectionStart(OutputText.getText().length());
				OutputText.setSelectionEnd(OutputText.getText().length());
				if(!isOpening || Information.equals("系统提示:对方退出了聊天框。")){
					return;
				}//if
			}//try
			catch (IOException e) {} 
		}//while
	}//run
	public void actionPerformed(ActionEvent e) {
		try {
			out.writeUTF("系统提示:对方退出了聊天框。");
			isOpening=false;
		}//try
		catch (IOException e1) {} 
		frame.setVisible(false);
	}//actionPerformed
	@Override
	public void windowActivated(WindowEvent arg0) {
       //System.out.println(1);
	}
	@Override
	public void windowClosed(WindowEvent arg0) {
       //System.out.println(2);
	}
	@Override
	public void windowClosing(WindowEvent arg0) {
		try {
			out.writeUTF("系统提示:对方退出了聊天框。");
			isOpening=false;
		} catch (IOException e1) {} 
	}
	@Override
	public void windowDeactivated(WindowEvent arg0) {
        //System.out.println(4);
	}
	@Override
	public void windowDeiconified(WindowEvent arg0) {
        //System.out.println(5);
	}
	@Override
	public void windowIconified(WindowEvent arg0) {
        //System.out.println(6);
	}
	@Override
	public void windowOpened(WindowEvent arg0) {
        //System.out.println(7);
	}
}

class Communication extends Thread implements ActionListener,WindowListener{
    private Socket server;
    private JFrame frame;
    private DataInputStream in;
    private DataOutputStream out;
    private JTextField InputText;
    private JTextArea OutputText;
    private boolean isOpening;
    private boolean Accept;
    Communication(JFrame frame,int port){
		//给本机传输文件
                this.frame=frame;
                isOpening=true;
                Accept=false;
                try {
                        System.out.println("建立与其它文件传输软件的连接");
                        //InetAddress.getLocalHost()获取本机的IP地址
                        server=new Socket(InetAddress.getLocalHost(),port);
                        server.setSoTimeout(60000);//设置超时时间为一分钟
                        //建立网络输入输出流,用于发送各种各样的信息(非文件)
                        in=new DataInputStream(server.getInputStream());
                        out=new DataOutputStream(server.getOutputStream());
                        Accept=true;
                        System.out.println("向对方发出发起聊天的指令");
                        out.writeUTF("发起聊天");
                        if(in.readBoolean()){
                                System.out.println("对方同意,建立窗口");
                                setFrame();
                                start();
			}
		} catch (IOException e1) {
                        if(Accept){JOptionPane.showMessageDialog(frame,"对方接受超时","错误",JOptionPane.ERROR_MESSAGE);}
                        else {JOptionPane.showMessageDialog(frame,"无法与对方连接,或者请检查IP地址和端口是否有输错,或者网络已断开","错误",JOptionPane.ERROR_MESSAGE);}
                }
	}//Communication
	Communication(JFrame frame,int port,String IP){
		//给本机传输文件
		this.frame=frame;
                isOpening=true;
                Accept=false;
		try {
			System.out.println("建立与其它文件传输软件的连接");
			//InetAddress.getLocalHost()获取本机的IP地址
			server=new Socket(IP,port);
            server.setSoTimeout(60000);//设置超时时间为一分钟
			//建立网络输入输出流,用于发送各种各样的信息(非文件)
			in=new DataInputStream(server.getInputStream());
			out=new DataOutputStream(server.getOutputStream());
                        Accept=true;
			out.writeUTF("发起聊天");
			if(in.readBoolean()){
				setFrame();
				start();
			}
		} catch (IOException e1) {             
                        if(Accept){JOptionPane.showMessageDialog(frame,"对方接受超时","错误",JOptionPane.ERROR_MESSAGE);}
                        else {JOptionPane.showMessageDialog(frame,"无法与对方连接,或者请检查IP地址和端口是否有输错,或者网络已断开","错误",JOptionPane.ERROR_MESSAGE);}
                }
	}//Communication
	public void run(){
		frame.setVisible(true);
		while(true){
			try {
				String Information=in.readUTF();
				OutputText.append(Information);
				OutputText.setSelectionStart(OutputText.getText().length());
				OutputText.setSelectionEnd(OutputText.getText().length());
				if(isOpening && Information.equals("系统提示:对方退出了聊天框。")){
					return;
				}//if
			} catch (IOException e) {} 
		}//while
	}
	public void setFrame(){
				//创建并设置窗体
				frame=new JFrame("聊天工具");
				//添加WindowListener事件
				frame.addWindowListener(this);
				//创建并设置菜单栏
				JMenuBar menubar=new JMenuBar();
				//创建并设置菜单"文件"
				JMenu menu=new JMenu("操作");
				//创建并设置子菜单"关闭"
				JMenuItem Close=new JMenuItem("关闭");	
				//创建输入框
				InputText=new JTextField();
				//创建聊天框
				OutputText=new JTextArea();
				//设置聊天框滚动条
				JScrollPane RollPane=new JScrollPane(OutputText);
				//聊天框设置不可修改
				OutputText.setEditable(false);
				//设置聊天框大小
				RollPane.setPreferredSize(new Dimension(250,100));
				//聊天框设置自动换行
				OutputText.setLineWrap(true);
				
				//窗体关闭时退出程序
				frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);		
				//设置窗口大小
				frame.setSize(500,400);
				//设置窗口位置
				frame.setLocation(250,250);
				//是否可见
				frame.setVisible(true);
				//是否可改变大小
				frame.setResizable(true);
				//显示窗体
				frame.setVisible(true);
				
				
				//窗体添加菜单栏,菜单栏放在窗体北侧
				frame.add(menubar,BorderLayout.NORTH);
				//窗体添加输入框,输入框放在窗体南侧
				frame.add(InputText,BorderLayout.SOUTH);
				//窗体添加聊天框滚动条(包含聊天框)
				frame.add(RollPane,BorderLayout.CENTER);
				//菜单栏添加菜单"关闭"
				menubar.add(menu);
				//菜单"操作"添加子菜单"关闭"
				menu.add(Close);
				Close.addActionListener(this);
				InputText.addActionListener(new ActionListener(){
					public void actionPerformed(ActionEvent e) {
						try {
						    Date nowTime=new Date();//时间类
							OutputText.append(nowTime.toString()+"\r\nMe:"+InputText.getText()+"\r\n");
							out.writeUTF(nowTime.toString()+"\r\nHim/Her:"+InputText.getText()+"\r\n");
							OutputText.setSelectionStart(OutputText.getText().length());
							OutputText.setSelectionEnd(OutputText.getText().length());
							InputText.setText(null);
						} catch (IOException e1) {}
					}
				});
	}
	public void actionPerformed(ActionEvent e) {
		try {
			out.writeUTF("系统提示:对方退出了聊天框。");
			isOpening=false;
		} catch (IOException e1) {} 
		frame.setVisible(false);
	}
	
    @Override
	public void windowActivated(WindowEvent arg0) {
       //System.out.println(1);
	}
    
    @Override
	public void windowClosed(WindowEvent arg0) {
       //System.out.println(2);
	}
    
    @Override
	public void windowClosing(WindowEvent arg0) {
		try {
			out.writeUTF("系统提示:对方退出了聊天框。");
			isOpening=false;
		} catch (IOException e1) {} 
	}

    @Override
	public void windowDeactivated(WindowEvent arg0) {
    	//System.out.println(4);
	}

    @Override
	public void windowDeiconified(WindowEvent arg0) {
        //System.out.println(5);
	}

    @Override
	public void windowIconified(WindowEvent arg0) {
	   //System.out.println(6);
	}

    @Override
	public void windowOpened(WindowEvent arg0) {
       //System.out.println(7);
	}
}

class Accept_File extends Thread implements ActionListener{
	private Socket client;
	private String FileName;//文件名字
	private String FileDirectory;//设置文件路径
	private String FilePath;
	private int FileBytesSize;//文字总字节数
	private JProgressBar PB;//进度条
	private JFrame frame;//窗口
	private JButton pause;
	private JLabel PIC;//显示文件的图标和名字
	private JLabel Byte_NUM;//显示文件字节数
	private Box boxV;//把所有组件打包成一个箱子
	private boolean isCancel;//如果按了取消键
	private boolean isPause;//如果按了暂停键
	private InputStream _in;
	private DataInputStream in;
	private DataOutputStream out;
	Accept_File(JFrame frame,Socket client) throws IOException{
		this.frame=frame;
		this.client=client;
		//构造网络输入输出流
		in=new DataInputStream(client.getInputStream());
		out=new DataOutputStream(client.getOutputStream());
		//接收文件
		InputStream netIn=client.getInputStream();
    	        _in=new DataInputStream(new BufferedInputStream(netIn));
		start();
	}
	public void run(){
		
		try {
			//每次server.accept()和new server(IP,post)后只能传输一次文件
			while(true){
				System.out.println("本机接收对方发送过来的文件名字");
				FileName=in.readUTF();
				renew();
				System.out.println(FileName);		
				if(acceptInformation()){
					FileAccept();
					pause.setText("打开文件所在的位置");
					break;
				}//if
			}//while
		} catch (IOException e) {System.out.println("无法获取文本文件");}
	}//run
	
	public void FileAccept(){
		try{
        	System.out.println("获取文件大小");
            //获取文件大小
            int FileBytesSize=this.in.readInt();
            System.out.println(FileBytesSize+"文件大小获得");
            
            //使用本地文件系统接受网络数据并存为新文件
            File file=new File(FileDirectory+FileName);
            file.createNewFile();
            RandomAccessFile raf=new RandomAccessFile(file,"rw");
            
            //创建一个byte数组作为文件读取缓冲流
			byte[] buf=new byte[2048];       
			System.out.println("开始读取文件");
			//开始读取文件
			int sum=0;
			int s=_in.read(buf);//读取2048长度的数据,s返回这段数据的长度,如果文件剩余数据不足2048,s<2048
			
			while(s!=-1){//s为-1表示文件已经没有可以再次读取的数据了。
				//按钮事件
				if(isPause){
					try {hangUP();} //按下暂停键的时候线程停在这里
					catch (Exception e) 
					{e.printStackTrace();}
                }//if
				if(isCancel){
					return;//按下取消键的时候线程终止
				}//if
				raf.write(buf,0,s);//将数据写往文件
				sum+=s;
				
				if(FileBytesSize>=1000000){
					Byte_NUM.setText(sum/1000000+"/"+FileBytesSize/1000000+"MB");   //标签:文件大小(以MB来计算)
				}
				else if(FileBytesSize>=1000){
					Byte_NUM.setText(sum/1000+"/"+FileBytesSize/1000+"KB");   //标签:文件大小(以KB来计算)
				}
				else{
					Byte_NUM.setText(sum+"/"+FileBytesSize+"Byte");  //标签:文件大小(以Byte来计算)
				}
				PB.setValue((int)(((double)sum/(double)FileBytesSize)*100));  //进度条:显示进度
			    //System.out.println((int)(((double)sum/(double)FileBytesSize)*100));
				s=_in.read(buf);
			}//while
			System.out.println("关闭");
			//关闭
			raf.close();
			_in.close();
			client.close();
		}//try
		catch(IOException e2){
			if(e2.getMessage().equals("Connection reset by peer: socket write error")){
				JOptionPane.showMessageDialog(frame, "本机网络中断","错误",JOptionPane.ERROR_MESSAGE);
			}//if
			else if(e2.getMessage().equals("Read timed out")){
				JOptionPane.showMessageDialog(frame, "对方网络中断或取消了发送","错误",JOptionPane.ERROR_MESSAGE);
			}//else if
		}//catch
	}//FileAccept
	
	public boolean acceptInformation(){
		boolean choice=false;
		try {
			while(true){
				System.out.println("是否接受文件");
				if(JOptionPane.showConfirmDialog(frame, "对方要求向您发送文件  "+FileName+" 您是否接受?")==0){
					System.out.println("发送true给对方");
					choice=true;
					if(ChooseDirectory()){
						PIC.setText(FileName);
						frame.add(boxV);
						frame.pack();
						break;
					}//if
				}//if
				else{
						System.out.println("发送false给对方");
						choice=false;
						break;
					}//else
			}//while
			out.writeBoolean(choice);
			return choice;
		}//try 
		catch (IOException e) {}
		return choice;
	}//acceptInformation
	
	public boolean ChooseDirectory(){
		JFileChooser JFC=new JFileChooser("D:\\");
		JFC.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		int s=JFC.showOpenDialog(JFC);
		if(s==0){
			FilePath=JFC.getSelectedFile().getAbsolutePath();
			FileDirectory=FilePath+"\\";
			return true;
		}
		else {
			return false;
		}//else
	}//ChooseDirectory
	
	public void renew(){
		isCancel=false;
		isPause=false;
		
		//创造一个横向的箱子
		boxV=Box.createHorizontalBox();
		PIC=new JLabel();
		PIC.setBounds(new Rectangle(100,100));
		boxV.add(PIC);
				
		//进度条
		PB=new JProgressBar(0,100);
		PB.setStringPainted(true);
		boxV.add(PB);
				
		//字节数
		Byte_NUM=new JLabel("0/"+String.valueOf(FileBytesSize));
		boxV.add(Byte_NUM);
		
		//暂停按钮
		pause=new JButton("暂停");
		boxV.add(pause);
		pause.addActionListener(this);
		
		//取消按钮
		JButton cancel=new JButton("取消");
		boxV.add(cancel);
		cancel.addActionListener(this);
				
		//刷新一下
		frame.setVisible(false);
		frame.setVisible(true);
	}//renew
	public void actionPerformed(ActionEvent e) {
		if(((JButton)e.getSource()).getText()=="取消"){
			isCancel=true;//按下取消键的时候终止线程
			boxV.setVisible(false);
			try {
				this.out.write(-1);
			} catch (IOException e1) {
			}
		}
		else if(((JButton)e.getSource()).getText()=="暂停"){
			isPause=true;//按下暂停键的时候暂停线程。
			((JButton)e.getSource()).setText("继续");
		}
		else if(((JButton)e.getSource()).getText()=="继续"){
			isPause=false;
			restart();//按下继续键的时候继续执行线程
			((JButton)e.getSource()).setText("暂停");
		}
		else if(((JButton)e.getSource()).getText()=="打开文件所在的位置"){
			try{
				String[] cmd = new String[5];
				String url = FilePath;    
				cmd[0] = "cmd";     
				cmd[1] = "/c";     
				cmd[2] = "start";    
				cmd[3] = " ";    
				cmd[4] = url;   
				Runtime.getRuntime().exec(cmd);  
			} catch (IOException e1) {}
		}//if “打开文件所在的位置”
	}
	private synchronized void hangUP()throws InterruptedException{
		wait();
	}
	private synchronized void restart(){
		notifyAll();
	}
}

class Delivery_File extends Thread implements ActionListener{
	private JFrame frame;//窗口
	private Socket server;
	private DataInputStream in;
	private DataOutputStream out;
	private String FileName;//文件名字
	private int FileBytesSize;//文字总字节数
	private File file;//文件
	private boolean isCancel;//如果按了取消键
	private boolean isPause;//如果按了暂停键
	private Box boxV;//把所有组件打包成一个箱子
	private JLabel Byte_NUM;//显示文件字节数
	private JProgressBar PB;//进度条
	private JLabel PIC;//显示文件的图标和名字
	private JButton Delivery;//发送按钮
	private JButton Cancel;//取消按钮
	private Icon icon;//图标
	private OutputStream netOut;
	private OutputStream doc;
	
	Delivery_File(int port,JFrame frame){
		//给本机传输文件
		this.frame=frame;
		try {
			System.out.println("建立与其它文件传输软件的连接");
			//InetAddress.getLocalHost()获取本机的IP地址
			server=new Socket(InetAddress.getLocalHost(),port);
			//建立网络输入输出流,用于发送各种各样的信息(非文件)
			in=new DataInputStream(server.getInputStream());
			out=new DataOutputStream(server.getOutputStream());
			//建立一个网络输入输出缓冲流,用于发送文件
			netOut=server.getOutputStream();
			doc=new DataOutputStream(new BufferedOutputStream(netOut));
			out.writeUTF("传送文件");
			ChooseFile();
			if(FileName!=null){
				SetABox();
			}//if
		} catch (IOException e1) {JOptionPane.showMessageDialog(frame,"无法与对方连接,请检查IP地址和端口是否有输错,或者网络已断开","错误",JOptionPane.ERROR_MESSAGE);}
	}//Delivery_File
	Delivery_File(int port,JFrame frame,String IP){
		//给其它电脑传输文件
		this.frame=frame;
		try {
			System.out.println("建立与其它文件传输软件的连接");
			//IP:对方的IP
			server=new Socket(IP,port);
			//建立网络输入输出流,用于发送各种各样的信息(非文件)
			in=new DataInputStream(server.getInputStream());
			out=new DataOutputStream(server.getOutputStream());
			//建立一个网络输入输出缓冲流,用于发送文件
			netOut=server.getOutputStream();
			doc=new DataOutputStream(new BufferedOutputStream(netOut));
			out.writeUTF("传送文件");
			ChooseFile();
			if(FileName!=null){
				SetABox();
			}//if
		} catch (IOException e1) {JOptionPane.showMessageDialog(frame,"无法与对方连接,请检查IP地址和端口是否有输错,或者网络已断开","错误",JOptionPane.ERROR_MESSAGE);}
	}//Delivery_File
	
	public void SetABox(){
		isCancel=false;
		isPause=false;
		
		try {
			//获取文件的字节大小
			InputStream IS=new FileInputStream(file);
			FileBytesSize=IS.available();
		} catch (Exception e1) {}
	
		//获取图标
		FileSystemView view=FileSystemView.getFileSystemView();
		icon=view.getSystemIcon(file);
	
		//创造一个横向的箱子
		boxV=Box.createHorizontalBox();
		PIC=new JLabel(FileName);
		PIC.setBounds(new Rectangle(100,100));
		PIC.setIcon(icon);
		boxV.add(PIC);
	
		//进度条
		PB=new JProgressBar(0,100);
		PB.setStringPainted(true);
		boxV.add(PB);
	
		//字节数
		Byte_NUM=new JLabel("0/"+String.valueOf(FileBytesSize)+"Byte");
		boxV.add(Byte_NUM);
	
		//发送按钮
		Delivery=new JButton("发送");
		Delivery.addActionListener(this);
		boxV.add(Delivery);
	
		//取消按钮
		Cancel=new JButton("取消");
		boxV.add(Cancel);
		Cancel.addActionListener(this);
	
		frame.add(boxV);
		//刷新一下
		frame.setVisible(false);
		frame.setVisible(true);	

		frame.pack();//把窗口按组件大小变换合适的大小
	}
	
	public void ChooseFile(){
		FileDialog filedialog=new FileDialog(frame,"打开",FileDialog.LOAD);
		filedialog.setVisible(true);
		if(filedialog.getDirectory()==null)return;//按取消的时候
		String FileDirectory=filedialog.getDirectory();//获取文件路径 D:\Backup\桌面\
		//String FileName=filedialog.getName();//filedlg0
		FileName=filedialog.getFile();//获取文件名字     XXX.XXX
		System.out.println(1+" "+FileName);
		String Path=FileDirectory+FileName;//获取路径
		file=new File(Path);
	}//ChooseFile()


	public void DeliveryFile(){
		int sum=0;//变量sum用于计算已经传输了多少字节
		int s;
		try {
			System.out.println("给对方发送文件名字");
	    	//向对方发送文件名字
	    	out.writeUTF(FileName);
	    	System.out.println("对方接收成功");
	    	System.out.println("看对方是否接收文件");
	    	//询问对方是否同意接受文件
	    	if(in.readBoolean()){//-----------------------------------------------------
	    		System.out.println("对方接收文件,向对方发送文件字节大小");
	    		//向对方发送文件大小
	    		out.writeInt(FileBytesSize);
	    	
	    		//创建文件输入流
	    		FileInputStream in=new FileInputStream(file);
			
	    		System.out.println("开始传输文件");
	    		//创建一个byte数组作为文件读取缓冲流
	    		byte[] buf=new byte[2048];
	    		s=in.read(buf);//从文件读取2048长度的数据,s返回这段数据的长度,如果文件剩余数据不足2048,s<2048
	    		while(s!=-1){//s为-1表示文件已经没有可以再次读取的数据了。
	    			//按钮事件
	    			if(isPause){
	    				try {hangUP();} 
	    				catch (Exception e) {e.printStackTrace();}//按下暂停键的时候线程停在这里
	    			}//if
	    			if(isCancel){
	    				return;//按下取消键的时候线程终止}
	    			}//if
	    			
	    			//文件传输
	    			doc.write(buf,0,s);
	    			doc.flush();
	    				
	    			
	    			//显示传输进度
	    			sum+=s;  //sum:当前已读的字节大小
	    			if(FileBytesSize>=1000000){
	    				Byte_NUM.setText(sum/1000000+"/"+FileBytesSize/1000000+" MB");   //标签:文件大小(以MB来计算)
	    			}//if
	    			else if(FileBytesSize>=1000){
						Byte_NUM.setText(sum/1000+"/"+FileBytesSize/1000+" KB");   //标签:文件大小(以KB来计算)
	    			}//else if
	    			else{
	    				Byte_NUM.setText(sum+"/"+FileBytesSize+" Byte");   //标签:文件大小(以Byte来计算)
	    			}//else
	    			PB.setValue((int)(((double)sum/(double)FileBytesSize)*100));  //进度条:显示进度
	    			s=in.read(buf);
	    		}//while
	    		System.out.println("关闭");
	    		in.close();
	    		doc.close();
	    		out.close();
	    		server.close();
	    		System.out.println("传输完成!");
	    	}//if
	    	else JOptionPane.showMessageDialog(frame, "对方拒绝接受文件","警告",JOptionPane.ERROR_MESSAGE);
	    }//try
		catch (IOException e) {			
			if(e.getMessage().equals("Connection reset by peer: socket write error")){
				JOptionPane.showMessageDialog(frame, "本机网络中断","错误",JOptionPane.ERROR_MESSAGE);
			}//if
			else if(e.getMessage().equals("Read timed out")){
				JOptionPane.showMessageDialog(frame, "对方网络中断或取消了发送","错误",JOptionPane.ERROR_MESSAGE);
			}//else if
			}
			boxV.setVisible(false);
	}//DeliveryFile()
	
	public void run(){
		DeliveryFile();
	}//run
	
	public void actionPerformed(ActionEvent e) {
		if(((JButton)e.getSource()).getText()=="发送"){
			System.out.println("按下发送键");
			start();//按下发送键的时候启动线程
			((JButton)e.getSource()).setText("暂停");
		}//if
		else if(((JButton)e.getSource()).getText()=="取消"){
			System.out.println("按下取消键");
			isCancel=true;//按下取消键的时候终止线程
			boxV.setVisible(false);
		}//else if
		else if(((JButton)e.getSource()).getText()=="暂停"){
			System.out.println("按下暂停键");
			isPause=true;//按下暂停键的时候暂停线程。
			((JButton)e.getSource()).setText("继续");
		}//else if
		else if(((JButton)e.getSource()).getText()=="继续"){
			System.out.println("按下继续键");
			isPause=false;
			restart();//按下继续键的时候继续执行线程
			((JButton)e.getSource()).setText("暂停");
		}//else if
	}//actionPerformed
	private synchronized void hangUP()throws InterruptedException{
		wait();
	}//hangUP
	private synchronized void restart(){
		notifyAll();
	}//restart
}//Delivery_File

class ViewOfFileTransfer extends Thread implements ActionListener{
	private JFrame frame;//文件传输软件窗口
	private JFrame showIP_frame;//显示本机IP地址的窗口
	private JFrame setIP_frame;//设置IP地址的窗口
	private JFrame About_frame;//"关于"的窗口
	private JMenuItem showport;//显示端口
	private JMenuItem Communicate;//发起聊天
	private JMenuItem DeliveryFile;//发送文件
	private JMenuItem setIP;//设置IP地址的菜单子项
	private JMenuItem showIP;//显示本机的IP地址
	private JMenuItem About;//关于
	private ServerSocket server;
	private int port;//端口号
	private int port1;//自己的端口号
	private String IP;//IP地址
	private boolean isLocalPC;//为true则选择的是本机
	private boolean First;//用于在设置IP地址的时候,控制文本框只有第一次点击时候才会清空
	private JTextField JTF;//设置IP地址的窗口里的文本框
	ViewOfFileTransfer(){
		System.out.println("建立窗口");
		//首先建立文件传输软件的窗口
		frame=new JFrame("文件传输");
		frame.setBounds(343,71,480,284);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		//窗口设置BoxLayout布局
		frame.setLayout(new BoxLayout(frame.getContentPane(),BoxLayout.Y_AXIS));
		
		//建立菜单栏
		JMenuBar MMenu=new JMenuBar();
		
		//建立菜单项“操作”
		JMenu File=new JMenu("操作");
		JMenu Help=new JMenu("帮助");
		
		//菜单子项初始化
		showport=new JMenuItem("显示端口");
		Communicate=new JMenuItem("发起聊天");
		DeliveryFile=new JMenuItem("发送文件");
		setIP=new JMenuItem("设置连接指向");
		showIP=new JMenuItem("显示IP地址");
		About=new JMenuItem("关于");
		
		//菜单子项添加事件
		showport.addActionListener(this);
		Communicate.addActionListener(this);
		DeliveryFile.addActionListener(this);
		setIP.addActionListener(this);
		showIP.addActionListener(this);
		About.addActionListener(this);
		
		//菜单项添加菜单子项
		File.add(showport);
		File.add(DeliveryFile);
		File.add(Communicate);
		File.add(setIP);
		File.add(showIP);
		Help.add(About);
		
		//窗口添加菜单栏,菜单栏添加菜单
		MMenu.add(File);
		MMenu.add(Help);
		frame.setJMenuBar(MMenu);
		
		//窗口显示
		frame.setVisible(true);
		
		//输入端口号
		boolean Input=true;
		while(Input){
			String str=JOptionPane.showInputDialog(frame,"请输入端口号");
			if(str!=null  &&  str.matches("[0-9]+")){
				int port=Integer.parseInt(str);
				if(port>1024&&port<=65535){
					Input=false;
					this.port1=port;
					try{
						server=new ServerSocket(port);
					/*	//设置连接超时时间是30秒钟
						server.setSoTimeout(30000);*/
					}//try
					catch(IOException e1){}
				}//if
				else{
					JOptionPane.showMessageDialog(frame, "您输入了非法端口","警告",JOptionPane.WARNING_MESSAGE);
				}//else
			}//if
			else{
				JOptionPane.showMessageDialog(frame, "您输入了非数字序列","警告",JOptionPane.WARNING_MESSAGE);
			}//else
		}//while
		
		//连接对象默认为本机
		isLocalPC=true;
		
		//建立各种窗口
		setIP_JFrame();
		setshowIP_frame();
		
		
		//启动线程,接受来自其它传输软件的连接
		start();
		
		//输入对方的端口号
		Input=true;
		while(Input){
			String str=JOptionPane.showInputDialog(frame,"请输入对方的端口号");
			if(str!=null  &&  str.matches("[0-9]+")){
				int port=Integer.parseInt(str);
				if(port>1024&&port<=65535){
					Input=false;
					this.port=port;
				}//if
				else{
					JOptionPane.showMessageDialog(frame, "您输入了非法端口","警告",JOptionPane.WARNING_MESSAGE);
				}//else
			}//if
			else{
				JOptionPane.showMessageDialog(frame, "您输入了非数字序列","警告",JOptionPane.WARNING_MESSAGE);
			}//else
		}//while
		
		set_AboutMenu();
	}//ViewOfFileTransfer
	public void run(){
		//循环,对方按下发送文件的时候接受到信息,然后启动接收文件的线程
		while(true){
			try {
				System.out.println("等待另一个文件传输软件来连接");
				//等待另一个文件传输软件来连接
				Socket client=server.accept();
				DataInputStream in=new DataInputStream(client.getInputStream());
				String choice=in.readUTF();
				client.setSoTimeout(60000);//设置连接超时时间是一分钟
				//有另一个文件传输软件点击了发送文件
				System.out.println("与某个文件传输软件建立联系"+choice);
				if(choice.equals("传送文件")){
					//建立接收文件线程
					System.out.println("传送文件");
					new Accept_File(frame,client);
				}
				else if(choice.equals("发起聊天")){
					if((JOptionPane.showConfirmDialog(frame,"对方向您发起聊天,您是否接受"))==0){
						System.out.println("接受聊天邀请");
						new Accept_Communication(client);
					}else{
						System.out.println("拒绝聊天邀请");
						DataOutputStream out=new DataOutputStream(client.getOutputStream());
						out.writeBoolean(false);
					}
				}
			}//try
			catch(IOException e2){System.out.println("连接超时!");}
		}//while
	}//run
	
	public void setshowIP_frame(){
		showIP_frame=new JFrame("显示本机的IP地址");
		showIP_frame.setBounds(474,233,327,70);
		showIP_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		showIP_frame.setLayout(new FlowLayout());
		
		JLabel label=new JLabel("您的IP地址是:");
		showIP_frame.add(label);
		
		
		try {
			String s=InetAddress.getLocalHost().toString();
			s=s.replaceAll(".+/", "");
			JTextField JTF=new JTextField(s);
			JTF.setEditable(false);
			showIP_frame.add(JTF);
		} catch (UnknownHostException e) {}
	}
	
	public void set_AboutMenu(){
		About_frame=new JFrame("关于");
		About_frame.setLayout(null);
		About_frame.setBounds(465,251,358,173);
		JLabel label=new JLabel("<html><br><img width=100 height=100 src=\"http://www.iconpng.com/png/windows-8-metro-invert/computer.png\"></br></html>");
		label.setBounds(10,10,100,120);
		JLabel author=new JLabel("By @author wuwave");
		author.setBounds(153,47,200,20);
		JLabel useTime=new JLabel("所用时间:");
		useTime.setBounds(153,70,200,20);
		useTime.setFont(new Font("新宋体",Font.BOLD,15));
		JLabel time=new JLabel("2014.12.13-2014.12.18");
		time.setFont(new Font("新宋体",Font.BOLD,15));
		time.setBounds(153,90,200,20);
		About_frame.add(label);
		About_frame.add(author);
		About_frame.add(useTime);
		About_frame.add(time);
		About_frame.setResizable(false);
	}
	
	public void setIP_JFrame(){
		//新建IP地址设置窗口
        First=true;
        setIP_frame=new JFrame("设置所要连接的对象");
        setIP_frame.setBounds(474,233,320,67);
        setIP_frame.setLayout(new FlowLayout());
        setIP_frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        ButtonGroup JCPG=new ButtonGroup();
        JRadioButton JCB1=new JRadioButton("本机");
        JRadioButton JCB2=new JRadioButton("其它电脑");
        JTF=new JTextField(12);
        JTF.setText("请输入其它电脑的IP地址");
        JTF.setEnabled(false);
        JCPG.add(JCB1);
        JCPG.add(JCB2);
        JCPG.setSelected(JCB1.getModel(), true);
        setIP_frame.add(JCB1);
        setIP_frame.add(JCB2);
        setIP_frame.add(JTF);
        JCB1.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
				//点击的如果是本机令isLocalPC为true,然后文本框不可输入
                isLocalPC=true;
                JTF.setEnabled(false);
		    }
		});
        JCB2.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e) {
                //点击的如果是其它电脑令isLocalPC为false,然后文本框可以输入
                isLocalPC=false;
                JTF.setEnabled(true);
            }
        });
        JTF.addMouseListener(new MouseListener(){
            public void mouseClicked(MouseEvent e) {
                if(First){
                    JTF.setText(null);
                    First=false;
                }
            }//mouseClicked
			
		    @Override
	        public void mouseEntered(MouseEvent e) {
		        //System.out.println(2);
		    }

	        @Override
	        public void mouseExited(MouseEvent e) {
	             //System.out.println(3);
	        }

		    @Override
			public void mousePressed(MouseEvent e) {
		        //	System.out.println(4);
		    }

	        @Override
	        public void mouseReleased(MouseEvent e) {
	            //	System.out.println(5);
	        }
	    });
        JTF.addCaretListener(new CaretListener(){
            public void caretUpdate(CaretEvent e) {
                //将文本框填写的IP地址赋给变量IP
                IP=((JTextField)e.getSource()).getText();
            }//caretUpdate
        });
    }//setIP_JFrame
	
    public void actionPerformed(ActionEvent e){
        if(e.getSource()==showport){
            //按下显示端口的菜单子项
            //查看该文件传输软件所设置的端口
            JOptionPane.showMessageDialog(frame, "您设置的端口号是"+port1);
        }//if
        else if(e.getSource()==DeliveryFile){
            //按下发送文件
            //根据设置的是本机还是其它电脑建立发送文件线程
            System.out.println("与另一个文件传输软件连接");
            if(port!=0){
                //根据设置的是本机还是其它电脑的IP设置发送文件线程
                if(isLocalPC){
                	System.out.println("向本机发送文件");
                    new Delivery_File(port,frame);
                }//if
                else{
                	System.out.println("向对方发送文件");
                    new Delivery_File(port,frame,IP);
                }//else
            }//if
			else{
				JOptionPane.showMessageDialog(frame, "请先输入端口号");
			}//else
		}//else if
		else if(e.getSource()==setIP){
			//显示设置IP的窗口
			setIP_frame.setVisible(true);
		}//else if
		else if(e.getSource()==showIP){
			//显示设置IP的窗口
			showIP_frame.setVisible(true);
		}//else if
		else if(e.getSource()==About){
			About_frame.setVisible(true);
		}//else if
		else if(e.getSource()==Communicate){
			System.out.println("发起聊天");
			if(port!=0){
				//根据设置的是本机还是其它电脑的IP设置发送文件线程
				if(isLocalPC){
					System.out.println("向本机发起聊天");
					new Communication(frame,port);
				}//if
				else{
					System.out.println("向对方发起聊天");
					new Communication(frame,port,IP);
				}//else
			}//if
			else{
				JOptionPane.showMessageDialog(frame, "请先输入端口号");
			}//else
		}//if(Communicate)
	}//actionPerformed
}



文件传输窗口菜单栏:

“操作菜单栏”

1.显示端口

2.发送文件

3.发起聊天

4.设置连接指向

5.显示IP地址

抱歉!评论已关闭.