您好我相对较新的Java和网络方面的新手,我真的需要一些帮助吗?
过去几天我做了一些研究,因为我几天前对网络知之甚少。有类似的问题已经被问到但我似乎无法得到答案来帮助我。我再次对java网络很新,所以不知道如何解决这个问题。请帮忙......
我正在开发一个具有客户端/服务器关系的项目,我希望客户端能够通过套接字传输他们的个人音乐文件。每次我尝试这样做时,文件都会被创建,但它是空的。有网络经验的人可以帮我吗?
服务器代码:
public class Server extends JFrame {
//===============================
// FIELDS
//===============================
// connection essentials
private ServerSocket server;
private Socket connection;
private OutputStream outStream;
private InputStream inStream;
// file transfer essentials
private FileInputStream fileInStream;
private FileOutputStream fileOutStream;
private BufferedInputStream bufInStream;
private BufferedOutputStream bufOutStream;
private int bytesRead;
private int currentTot;
// frame components
private JTextArea textArea;
private JButton ok;
//===============================
// CONSTRUCTORS
//===============================
public Server(){
initComponents();
try {
runServer();
getStreams();
receiveFile();
} catch (IOException ex) {
System.out.print( "Error in constructor - Server" );
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
} // catch()
finally{
try {
close();
} catch (IOException ex) {
System.out.println( "Error in finally - attempt to close" );
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
} // catch()
} // finally
} // 0 Args
//===============================
// CLASS METHODS
//===============================
private void runServer() throws IOException {
*server = new ServerSocket( 7133, 100 );
connection = server.accept(); // accept clients conn attempt
textArea.setText( "Connection Established..." );
//connection.setTcpNoDelay( true ); // stops nagles algorithm by
// halting buffering (waiting to receive confirmaion from client)
} // runServer()
private void getStreams() throws IOException{
outStream = connection.getOutputStream();
outStream.flush();
inStream = connection.getInputStream();
textArea.append( "\n\nReceiving files..." );
} // getStreams()
private void close() throws IOException{
outStream.close();
inStream.close();
server.close();
} // close()
private void receiveFile() throws FileNotFoundException, IOException{
byte byteArray[] = new byte[ 10000000 ];
File receviedFile = new File( "YES.mp3" );
FileOutputStream FOS = new FileOutputStream( receviedFile );
try (ByteArrayOutputStream BOS = new ByteArrayOutputStream()) {
bytesRead = inStream.read(byteArray, 0, byteArray.length);
currentTot = bytesRead;
byteArray = BOS.toByteArray();
do {
bytesRead = inStream.read(
byteArray, 0, (byteArray.length - currentTot));
if (bytesRead >= 0)
currentTot += bytesRead;
if(currentTot == byteArray.length )
textArea.append( "\n\nFile recieved" );
} while (bytesRead > -1);
BOS.write(byteArray, 0, currentTot);
BOS.flush();
}
close();
} // receiveFiles()
private void initComponents() {
// textArea
textArea = new JTextArea();
this.add( textArea, BorderLayout.CENTER );
// send
ok = new JButton( "OK" );
this.add( ok, BorderLayout.SOUTH );
addListeners();
// frame fundamentals
this.setVisible( true );
this.setSize( 300, 150 );
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // initComponents()
private void addListeners() {
ok.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
textArea.setText( "File received and accepted" );
} // actionPerformed()
}); // addActionListeners()
} // addListeners()
//===============================
// SETTERS AND GETTERS
//===============================
public static void main(String[] args) {
Server server = new Server();
}
} // class{}
客户代码:
public class Client extends JFrame {
//===============================
// FIELDS
//===============================
// connection essentials
private Socket connection;
private InputStream inStream;
private OutputStream outStream;
// file transfer essentials
private FileInputStream fileInStream;
private FileOutputStream fileOutStream;
private BufferedInputStream bufInStream;
private BufferedOutputStream bufOutStream;
// frame components
private JTextArea textArea;
private JButton choose;
private JButton send;
// file
private File fileToSend;
//===============================
// CONSTRUCTORS
//===============================
public Client(){
initComponents();
try {
getConnected();
getStreams();
} catch (IOException ex) {
System.out.println( "Error in Client constructor" );
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} finally{
} // finally
}
//===============================
// CLASS METHODS
//===============================
private void getConnected() throws IOException {
connection = new Socket( InetAddress.getLocalHost(), 7133 );
textArea.setText( "Connection Established..." );
} // getConnected()
private void getStreams() throws IOException {
outStream = connection.getOutputStream();
outStream.flush();
inStream = connection.getInputStream();
} // getStreams()
private void close() throws IOException{
outStream.close();
inStream.close();
connection.close();
} // close()
private void sendFile( final File transfer )
throws FileNotFoundException, IOException{
byte fileInBytes[] = new byte[ (int) transfer.length() ];
fileInStream = new FileInputStream( transfer );
int start = 0;
textArea.setText( "Sending files...." );
while( (start = inStream.read()) > 0 )
outStream.write( fileInBytes, 0, fileInBytes.length );
bufInStream = new BufferedInputStream( fileInStream );
outStream.flush();
textArea.setText( "Transfer complete" );
close();
} // sendFile()
private void initComponents() {
// choose
choose = new JButton( "CHOOSE" );
this.add( choose, BorderLayout.NORTH );
// textArea
textArea = new JTextArea();
this.add( textArea, BorderLayout.CENTER );
// send
send = new JButton( "SEND" );
this.add( send, BorderLayout.SOUTH );
addListeners();
// frame fundamentals
this.setVisible( true );
this.setSize( 300, 150 );
this.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
} // initComponents()
private void addListeners() {
choose.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
getFile();
} // actionPerformed()
}); // addActionListeners()
send.addActionListener(
new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
new Runnable(){
@Override
public void run() {
try {
sendFile(fileToSend);
} catch (IOException ex) {
System.out.println(
"Error in send - actionPerformed");
Logger.getLogger(
Client.class.getName()).log(
Level.SEVERE, null, ex);
} // catch ()
} // run()
}; // runnable()
} // actionPerformed()
}); // addActionListeners()
} // addListeners()
private void getFile()
{
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(
JFileChooser.FILES_AND_DIRECTORIES );
int result = fileChooser.showOpenDialog( this );
// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION )
System.exit( 1 );
// getSelectedFile
fileToSend = fileChooser.getSelectedFile();
// display error if invalid
if ( ( fileToSend == null ) || ( fileToSend.getName().equals( "" ) ) )
{
JOptionPane.showMessageDialog( this, "Invalid Name",
"Invalid Name", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // end if
} // end method getFile
//===============================
// SETTERS AND GETTERS
//===============================
public static void main(String[] args) {
Client client = new Client();
}
} // class{}
答案 0 :(得分:0)
在你的receiveFile()方法中,你将收到的前10 MB(可能是所有内容)读入byteArray
。然后,在以下行中:
byteArray = BOS.toByteArray();
您丢弃之前的byteArray
值,包括您收到的所有数据,将其替换为BOS
的空内容。
您需要做的是将输入流读入缓冲区,然后从缓冲区写入FileOutputStream。没有必要打扰ByteArrayOutputStream。