这是我主界面,我想在这点开文件,然后可以发送给连接的人,目前的测试就是自己给自己发。
package com.fastSendFile;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.dnd.DnDConstants;
import java.awt.dnd.DropTarget;
import java.awt.dnd.DropTargetAdapter;
import java.awt.dnd.DropTargetDropEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.File;
import java.io.IOException;
import java.net.InetAddress;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTable;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableColumnModel;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
public class SendWindow {
// private static final SimpleDateFormat time = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
// private static Object lock1 = new Object();
private Object[] columnNames = { "用户名", "工作组","主机名","优先级", "IP地址", "port","" };
private String myName = "";
private UDP udpService;
private static SendWindow sendWindow;
int add =0;
int count=0,flag=0;
JFrame frame;
File f;
File file;
JButton reFresh;
JButton send;
JButton file_btn;
JButton open_file;
JLabel userOnline;
JLabel userCount;
JCheckBox packaging;
JCheckBox lock;
JTable table;
JTextArea inputArea;
JScrollPane scrollPaneTable;
JScrollPane scrollPaneFile;
JSplitPane jSplitPane;
JPanel panelSouth;
JPanel panelSouthNorth;
JPanel panelSouthSouth;
JPanel panelNorth;
JPanel panelNorthEast;
private JFileChooser filechooser;
private AddFileWindow addFileWindow;
String filename = "",filePath = "",filepath="";
long fileSize = 0;
int d = 0,port;
public Vector fileVector = new Vector();
private void createWindow() {
//分割容器
jSplitPane=new JSplitPane();//创建一个分割容器类
jSplitPane.setOrientation(JSplitPane.VERTICAL_SPLIT);//设置分割线方向
jSplitPane.setDividerSize(5);
jSplitPane.setDividerLocation(50);//设置分割线位于中央
//上半部分整体布局
panelNorth = new JPanel(new BorderLayout());
panelNorthEast = new JPanel(new BorderLayout());
panelNorth.add(panelNorthEast,BorderLayout.EAST);
jSplitPane.setTopComponent(panelNorth);
//下半部分整体布局
panelSouth = new JPanel(new BorderLayout());
panelSouthNorth = new JPanel();
panelSouthSouth = new JPanel();
inputArea = new JTextArea();
scrollPaneFile = new JScrollPane(inputArea);
scrollPaneFile.setPreferredSize(new Dimension(500, 150));
scrollPaneFile.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
file_btn = new JButton();
// panelSouthNorth.add(fileName);
file_btn.setVisible(false);
FlowLayout flowLayout2 = new FlowLayout(FlowLayout.CENTER , 10 , 10);
panelSouthSouth.setLayout(flowLayout2);
panelSouth.add(file_btn,BorderLayout.NORTH);
panelSouth.add(scrollPaneFile,BorderLayout.CENTER);
panelSouth.add(panelSouthSouth,BorderLayout.SOUTH);
jSplitPane.setBottomComponent(panelSouth);
DefaultTableModel tableModel = new DefaultTableModel(null, columnNames);
table = new JTable(tableModel){
private static final long serialVersionUID = 1L;
@Override
public boolean isCellEditable(int row, int column) {
return false;
}
};
scrollPaneTable = new JScrollPane();
scrollPaneTable.setPreferredSize(new Dimension(500, 150));
//scrollPaneTable.setPreferredSize(panelNorth.getPreferredSize());
scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scrollPane.setBounds(new Rectangle(76, 35, 257, 193));
//table.setFillsViewportHeight(true);
//panelNorth.add(table.getTableHeader(), BorderLayout.PAGE_START);
panelNorth.add(scrollPaneTable,BorderLayout.WEST);
// JScrollPane tableScroll = new JScrollPane();
JTableHeader header = table.getTableHeader();
header.setBounds(0, 0, 400, 20);
table.setBounds(0, 20, 400, 180);
DefaultTableColumnModel columnModel = (DefaultTableColumnModel) table.getColumnModel();
columnModel.removeColumn(columnModel.getColumn(6));
scrollPaneTable.setViewportView(header);
scrollPaneTable.setViewportView(table);
scrollPaneTable.setBounds(0, 0, 400, 200);
scrollPaneTable.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
//scrollPaneTable = new JScrollPane(table);
//scrollPaneTable.setPreferredSize(new Dimension(500, 150));
//scrollPaneTable.setPreferredSize(panelNorth.getPreferredSize());
//scrollPaneTable.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);
//scrollPane.setBounds(new Rectangle(76, 35, 257, 193));
//table.setFillsViewportHeight(true);
//panelNorth.add(table.getTableHeader(), BorderLayout.PAGE_START);
panelNorth.add(scrollPaneTable,BorderLayout.WEST);
//上半部分标签和按钮
userOnline = new JLabel("在线用户",JLabel.CENTER);
userCount = new JLabel("0",JLabel.CENTER);
reFresh = new JButton("刷新(R)");
panelNorthEast.add(userOnline,BorderLayout.NORTH);
panelNorthEast.add(userCount,BorderLayout.CENTER);
panelNorthEast.add(reFresh,BorderLayout.SOUTH);
//下半部分拖拽
DropTargetAdapter kgd=new DropTargetAdapter()
{
@Override
public void drop(DropTargetDropEvent dtde)
{
try
{
Transferable tf=dtde.getTransferable();
if(tf.isDataFlavorSupported(DataFlavor.javaFileListFlavor))
{
dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
List lt=(List)tf.getTransferData(DataFlavor.javaFileListFlavor);
Iterator itor=lt.iterator();
while(itor.hasNext())
{
f=(File)itor.next();
filename = f.getName();
fileSize = f.length();
filePath = f.getPath();
file_btn.setText(f.getName());
// fileName.setText(f.getPath());
//fileName.setText(f.getPath().substring(filePath.lastIndexOf("\\") + 1));
file_btn.setVisible(true);
fileVector.add(f);
add = 0;
// flag+=1;
//frame.removeAll();
// frame.repaint();
if(fileSize>0)
{
open_file.setEnabled(false);
}
}
dtde.dropComplete(true);
}
else
{
dtde.rejectDrop();
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
};
new DropTarget(inputArea,DnDConstants.ACTION_COPY_OR_MOVE,kgd);
file_btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
addFileWindow = AddFileWindow.createWindow(getInstance());
addFileWindow.frame.setVisible(true);
System.out.println("file_btn:"+f.getName()+f.length()+f.getPath());
addFileWindow.showFile(f.getName(),f.length(),f.getPath());
}
});
//下半部分按钮和复选按钮
open_file = new JButton("添加文件");
send = new JButton("发送(S)");
packaging = new JCheckBox("封装(E)");
packaging.setSelected(true);
lock = new JCheckBox("上锁(K)");
panelSouthSouth.add(open_file);
panelSouthSouth.add(send);
panelSouthSouth.add(packaging);
panelSouthSouth.add(lock);
open_file.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
filechooser = new JFileChooser();
filechooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
int option = filechooser.showDialog(null, "选择文件");
if (option == 0) {
file = filechooser.getSelectedFile();
filePath = file.getPath();
file_btn.setText(file.getName());
file_btn.setVisible(true);
add = 0;
}
}
});
packaging.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(packaging.isSelected()==false)
{
lock.setSelected(false);
lock.setEnabled(false);
}
}
});
//整个布局
frame = new JFrame("FastSend");
frame.setSize(595, 420);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
frame.setResizable(true);
frame.setContentPane(jSplitPane);
jSplitPane.setDividerLocation(0.5);
//frame.pack();
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent event) {
try {
udpService.broadcast("offline#");
} catch (IOException e) {
e.printStackTrace();
}
}
});
reFresh.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
frame.repaint();
}
});
send.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String msg = inputArea.getText();
if(add==1)
{
filepath = "";
}
else
{
filepath = filePath;
}
System.out.println("1111filepath:"+filepath);
if ((msg != null && msg.length() > 0) || (filepath != null && filepath.length() > 0))
{
List<Map<String, String>> selected = getSelected();
if (selected == null)
{
JOptionPane.showMessageDialog(null, "请选择发送对象!", "注意", JOptionPane.INFORMATION_MESSAGE);
return;
}
for (Map<String, String> map : selected)
{
String addr = map.get("addr");
int port = Integer.parseInt(map.get("port"));
try {
StringBuffer sb = new StringBuffer("msg#");
sb.append(myName);
msg = (msg != null && msg.length() > 0) ? msg : "null";
sb.append("#" + msg.replaceAll("#", "*"));
filepath = (filepath != null && filepath.length() > 0) ? filepath : "null";
sb.append("#" + filepath);
//if(addFileWindow.)
udpService.send(addr, port, sb.toString());
Vector sendList = new Vector( );
sendList.add(fileVector);
int[] selectRows = table.getSelectedRows();
InetAddress sendAddress;
DefaultTableModel model = (DefaultTableModel) table.getModel();
// for (int i = 0; i < selectRows.length; i++) {
// String addr = model.getValueAt(selectRows[i], 3).toString();
sendAddress=InetAddress.getByName( ( String ) model.getValueAt (selectRows[0] ,3 ) );
Thread clientThread=new Thread(new Client( sendList ,sendAddress));
clientThread.setPriority(6);
clientThread.start();
// }
} catch (IOException e1) {
e1.printStackTrace();
}
}
inputArea.setText(null);
file_btn.setVisible(false);
file_btn.setText("");
sendWindow.setVisible(false);
//filepath = "";
filename = "";
fileSize = 0;
filePath = "";
d= 1;
System.out.println("哈哈"+filepath);
}
else
{
System.out.println("wode..");
JOptionPane.showMessageDialog(null, "请输入内容或选择文件!", "注意", JOptionPane.INFORMATION_MESSAGE);
}
}
});
}
private void addRow(String userName,String hostGroup,String hostName,String Priority,String hostAddr, int hostPort) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[] { userName,hostGroup,hostName, Priority,hostAddr, hostPort });
}
private void rmRow(String addr) {
DefaultTableModel model = (DefaultTableModel) table.getModel();
for (int i = 0, j = table.getRowCount(); i < j; i++) {
String taddr = model.getValueAt(i, 2).toString();
if (taddr.equals(addr)) {
model.removeRow(i);
break;
}
}
}
private List<Map<String, String>> getSelected() {
int[] selectRows = table.getSelectedRows();
if (selectRows.length == 0) {
return null;
}
List<Map<String, String>> selected = new ArrayList<Map<String, String>>();
DefaultTableModel model = (DefaultTableModel) table.getModel();
for (int i = 0; i < selectRows.length; i++) {
String addr = model.getValueAt(selectRows[i], 3).toString();
port = Integer.parseInt(model.getValueAt(selectRows[i], 5).toString());
Map<String, String> map = new HashMap<String, String>();
map.put("addr", addr);
map.put("port", port + "");
selected.add(map);
}
return selected;
}
public void setInpuArea(String str) {
this.inputArea.setText(str);
}
public void setVisible(boolean b) {
frame.setVisible(b);
}
private SendWindow() throws IOException {
this.createWindow();
myName = System.getProperty("user.name");
udpService = new UDP();
ReceiveThread thread = new ReceiveThread();
thread.start();
udpService.broadcast("online#" + myName);
count++;
userCount.setText(count+"");
frame.repaint();
// TCP.init();
}
public static SendWindow getInstance() {
// synchronized (lock1) {
if (sendWindow == null) {
try {
sendWindow = new SendWindow();
} catch (IOException e) {
e.printStackTrace();
}
}
return sendWindow;
// }
}
class ReceiveThread extends Thread {
@Override
public void run() {
try {
while (true) {
Map<String, String> recMap = udpService.receive();
if (recMap != null && recMap.size() > 0) {
handlData(recMap);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
void handlData(Map<String, String> recMap) throws IOException {
String data = recMap.get("data").trim();
String hostName = recMap.get("hostName");
String hostGroup = "";
String hostAddr = recMap.get("hostAddr");
String Priority = "";
int hostPort = Integer.parseInt(recMap.get("hostPort"));
String[] dataArr = data.split("#");
if (dataArr[0].equals("online")) {// 收到上线消息后回复发消息给我的人
String userName = dataArr[1];
addRow(userName,hostGroup,hostName, Priority,hostAddr, hostPort);
udpService.send(hostAddr, hostPort, "reply#" + dataArr[1]);
return;
}
if (dataArr[0].equals("reply")) {// 更新在线table
if(!hostAddr.equals(InetAddress.getLocalHost().getHostAddress())){
String userName = dataArr[1];
addRow(userName,hostGroup,hostName, Priority,hostAddr, hostPort);
count++;
userCount.setText(count+"");
frame.repaint();
}
return;
}
if (dataArr[0].equals("offline")) {// 下线消息,更新table
rmRow(hostAddr);
count--;
userCount.setText(count+"");
frame.repaint();
return;
}
if (dataArr[0].equals("msg")) {// 接收文本消息
ReceiveWindow receiveWindow = ReceiveWindow.createWindow(getInstance());
String msg = dataArr[2].equals("null") ? "":dataArr[2];
String file = dataArr[3].equals("null") ? "":dataArr[3];
System.out.println("hhfilename"+file);
receiveWindow.showMsg(dataArr[1] + "/" + hostName, msg, file, hostAddr);
//addFileWindow.showFile( filename,fileSize,filePath);
return;
}
}
}
public static void main(String[] args) throws IOException {
SendWindow sendWindow = SendWindow.getInstance();
}
}
这是接收客户端,是端口选择的问题吗,我要怎么改呢T T
package com.fastSendFile;
import java.awt.GridLayout;
import java.util.*;
import java.net.*;
import java.io.*;
import javax.swing.*;
public class Client implements Runnable
{
private Vector Vname=new Vector();
private InetAddress address;
private Vector sendDir = new Vector();
private Vector fileVector = new Vector();
private long totalSize;
private long fileSize;
private String fileName;
private long receivedSize;
private long skipSize;
SendWindow sendWindow;
Client( Vector file , InetAddress address)
{
fileVector.addAll ( file ) ;
this.address = address;
}
public void getFiles(File file,String lastDir ,String localPath)
{
if(file.isFile())
{
totalSize += file.length();
sendDir.add (localPath);
Vname.add(new String(lastDir + "/"+file.getName()));
}
else if(file.isDirectory())
{
lastDir = lastDir + "/" + file.getName();
String strs[] = file.list();
for(int i = 0 ;i < strs.length; i ++)
{
File newfile = new File( file.getAbsolutePath() + "/" + strs[i] );
getFiles( newfile , lastDir , localPath );
}
}
}
public void run()
{
totalSize = 0;
String send = "";
try
{
byte[] buffer = new byte[1024];
Socket sendSocket = new Socket(address, 20);
DataInputStream in = new DataInputStream(sendSocket.getInputStream());
BufferedOutputStream outb = new BufferedOutputStream(sendSocket.getOutputStream(),512);
DataOutputStream out = new DataOutputStream(outb);
ObjectOutputStream oout = new ObjectOutputStream (out);
oout.writeObject ( fileVector );
oout.flush ();
ObjectInputStream oin = new ObjectInputStream ( in );
Vector accVector = (Vector) oin.readObject ();
if ( sendWindow.d ==1)
JOptionPane.showMessageDialog(null, "消息已发送","提示",JOptionPane.DEFAULT_OPTION);
for (int i = 0 ; i < accVector .size (); i ++)
{
File temp = (File) accVector.get ( i );
send += " " + temp.getName ();
getFiles( temp ,"",temp.getParent ());
}
//receive file
out.writeLong(totalSize);
out.flush();
int rSize;
File tempFile;
String tempString;
long count ;
JFrame frame = new JFrame();
frame.setTitle("正在发送文件");
JLabel lable1 = new JLabel();
JLabel lable2 = new JLabel();
JLabel lable3 = new JLabel();
frame.add( lable1,"North" );
frame.add( lable3,"South" );
receivedSize = 0;
JProgressBar bar = new JProgressBar ( 0 , (int)(totalSize/1024));
JProgressBar bar1 = new JProgressBar ();
bar.setForeground(new java.awt.Color(102, 255, 102));
bar.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)), "\u603b\u8fdb\u5ea6", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 13), new java.awt.Color(0, 0, 255)));
bar.setDoubleBuffered(true);
bar.setStringPainted ( true ) ;
bar1.setSize (320,20);
bar.setSize (320,20);
bar1.setForeground(new java.awt.Color(102, 255, 102));
bar1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(204, 204, 204)), "当前进度", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Dialog", 0, 13), new java.awt.Color(0, 0, 255)));
bar1.setDoubleBuffered(true);
bar1.setStringPainted ( true );
JPanel jp = new JPanel();
jp.setLayout ( new GridLayout( 3 , 1 ));
// jp.add ( new JLabel ("总进度: "));
jp.add ( bar );
// jp.add ( new JLabel( "当前进度: " ));
jp.add ( bar1 );
jp.add ( lable2 );
frame.add ( jp );
String Lmessage1 = "总共要发送: "+String.valueOf( totalSize / 1024) + " KB";
String Lmessage2 = "速度: 0";
lable1.setText( Lmessage1 );
lable2.setText( Lmessage2 );
lable3.setText ( "共" + Vname.size () + "个文件,已完成" + 0 + "个");
RandomAccessFile inFile;
frame.setBounds( 250 , 200 , 400 , 200);
frame.setResizable ( false );
frame.setVisible(true);
long baseTime = new Date().getTime();
for(int i = 0;i < Vname.size();i++)
{
count = 0;
lable3.setText ( "共" + Vname.size () + "个文件,已完成" + i + "个");
bar1.setMinimum ( 0 );
tempString = ( String ) Vname.get(i);
tempFile = new File( sendDir.get(i) + tempString);
fileSize = tempFile.length();
jp.setToolTipText ( "正发送:" + tempString.substring ( 1 ) );
out.writeLong(fileSize);
int locate = new Random().nextInt ( 1000 );
byte [] fileRandom = new byte [10];
if ( tempFile.length () < 1024 )
locate = -1 ;
else
fileRandom = getFile( locate,tempFile );
out.writeInt ( locate );
out.write ( fileRandom );
frame.setTitle ( "正发送文件:" + tempString.substring ( 1 ) );
bar1.setMaximum ( ( int )fileSize / 1024 );
bar1.setValue ( 0 );
byte data2[] = tempString.getBytes( "UTF-8" );
out.write(data2);
out.flush();
skipSize = in.readLong();
rSize = in.read(buffer);
String reBack = new String(buffer,0,rSize,"UTF-8");
if("S".equals(reBack))
{
receivedSize += fileSize;
count = fileSize;
bar.setValue ( (int) receivedSize / 1024);
bar1.setValue ((int) count / 1024);
continue;
}
else
{
if("C".equals(reBack))
{
receivedSize += skipSize;
count = skipSize;
bar.setValue ( ( int )receivedSize / 1024 );
bar1.setValue ( ( int )count /1024 );
inFile = new RandomAccessFile(tempFile, "r");
inFile.seek( skipSize );
}
else
{
inFile=new RandomAccessFile(tempFile, "r");
}
while((rSize = inFile.read(buffer)) != -1)
{
receivedSize += rSize;
count += rSize;
bar.setValue ( ( int )receivedSize / 1024 );
bar1.setValue ( ( int )count / 1024 );
lable2.setText("速度: "+
String.valueOf(receivedSize * 1000 / (new Date().getTime() - baseTime + 1) / 1024 )+" KB/s");
outb.write( buffer, 0 ,rSize );
}
outb.flush();
inFile.close();
}
}
fileSize = -1;
out.writeLong(fileSize);
out.writeInt ( -1 );
out.write( new byte [10]);
byte data3[] = "#发送完毕#".getBytes("UTF-8");
out.write(data3);
out.flush();
frame.setVisible(false);
JOptionPane.showMessageDialog(null, "发送完成!","提示", JOptionPane.DEFAULT_OPTION);
in.close();
out.close();
sendSocket.close();
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, "发送文件出错l:"+e,"错误", JOptionPane.ERROR_MESSAGE);
}
}
public static byte [] getFile( int n , File file)
{
byte [] b = new byte [10];
try
{
RandomAccessFile rf = new RandomAccessFile(file,"r");
rf.seek ( n );
rf.read ( b, 0 ,b.length);
rf.close ();
}
catch (Exception e)
{
}
return b;
}
}