2012-10-27 70 views
-2

大家好,我想开发应用程序传输/发送像SKYPE作品的文件。所以我使用套接字从一台计算机(客户端)到另一台计算机(客户端)。我能够使用this将文件从一个客户端传输到服务器。 code.But当我尝试发送相同的文件从服务器到第二个客户端。它与0字节传递也给套接字关闭异常,所以我尝试在客户端创建新的套接字对象。所以现在异常没有来,但文件不转移调试后,我发现该文件被服务器成功发送到客户端,但在客户端端socket无法读取数据和等待数据。我无法找到任何更好的解决方案。如果有任何人知道此内容告诉你me.If有文件传输任何其它解决方案相比还告诉me.Thanks提前 下面是我的代码发送文件从一个客户端到另一个客户端在java中使用套接字

Server code: 

public class ChatServer 
{ 

serversocket = new ServerSocket(1436); 
thread = new Thread(this); 
thread.start(); 

/*************Thread Implementation***************/ 
public void run() 
{ 
    /*********Accepting all the client connections and create a seperate thread******/ 
    while(thread != null) 
    { 
     try 
     { 
      /********Accepting the Server Connections***********/ 
      socket = serversocket.accept();    

    /******* Create a Seperate Thread for that each client**************/ 
      chatcommunication = new ChatCommunication(this,socket); 

      thread.sleep(THREAD_SLEEP_TIME);  
     } 
     catch(InterruptedException _INExc) { ExitServer(); } 
     catch(IOException _IOExc)   { ExitServer(); } 
    } 
} 

protected void SendGroupFile(Socket ClientSocket, String FileName,String GroupName,String UserName) throws IOException 
{ 
    try 
    { 
    // receive file from Client 
     byte [] mybytearray = new byte [filesize]; 
     InputStream is = socket.getInputStream(); 
     FileOutputStream fos = new FileOutputStream(Filepath); 
     BufferedOutputStream bos = new BufferedOutputStream(fos); 
     int bytesRead = is.read(mybytearray,0,mybytearray.length); 
     current = bytesRead; 

      do { 
      bytesRead =is.read(mybytearray, current, (mybytearray.length-current)); 
      System.out.println("Reading Bytes server"+bytesRead); 
      if(bytesRead >= 0) 
       current += bytesRead; 
     } while(bytesRead > -1); 

     bos.write(mybytearray,0,current); 
     bos.flush(); 
     bos.close(); 



    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } 
} 

     /***** Function To Send a File to Client **********/ 
protected void SendGroupFileClient(Socket ClientSocket, String FileName,String GroupName,String UserName) 
{ 
     try { 
      int m_userListSize = userarraylist.size(); 

       clientobject = GetClientObject(GroupName); 

       if(clientobject != null) 
       for(G_ILoop = 0; G_ILoop < m_userListSize; G_ILoop++) 
       { 

        clientobject = (ClientObject) userarraylist.get(G_ILoop); 
        if((clientobject.getGroupName().equals(GroupName)) && (!(clientobject.getUserName().equals(UserName)))) 
        { 
        {  

        File myFile = new File (Filepath); 
        byte [] mybytearray = new byte [(int)myFile.length()]; 
        FileInputStream fis = new FileInputStream(myFile); 
        BufferedInputStream bis = new BufferedInputStream(fis); 
        bis.read(mybytearray,0,mybytearray.length); 
        os = socket.getOutputStream(); 
        System.out.println("Sending..."); 
        os.write(mybytearray,0,mybytearray.length); 
        os.flush(); 
        os.close(); 
      } 

     }catch(IOException _IOExc) 
     { 
      _IOExc.printStackTrace(); 
     } 
} 
} 

ChatCommunication的.java

public class ChatCommunication implements Runnable,CommonSettings 
{ 
    Thread thread; 
Socket socket; 
DataInputStream inputstream; 
String RFC; 
ChatServer Parent; 

    /********Initialize the Socket to the Client***********/ 
ChatCommunication(ChatServer chatserver,Socket clientsocket) 
{    
    Parent = chatserver; 
    socket = clientsocket; 
    try 
    {  
    inputstream = new DataInputStream(new BufferedInputStream(socket.getInputStream()));  
    }catch(IOException _IOExc) { } 
    thread = new Thread(this); 
    thread.start(); 
} 

public void run() 
{ 
    while(thread != null) 
    { 
     try {    
      RFC = inputstream.readLine(); 

      if(RFC.startsWith("FILEGRUP")) 
      { 
       Parent.SendGroupFile(socket,RFC.substring(9,RFC.indexOf("!")),RFC.substring(RFC.indexOf("!")+1,RFC.indexOf("*")),RFC.substring(RFC.indexOf("*")+1));  
      } 

      if(RFC.startsWith("FILEGET")) 
      { 
       Parent.SendGroupFileClient(socket,RFC.substring(8,RFC.indexOf("!")),RFC.substring(RFC.indexOf("!")+1,RFC.indexOf("*")),RFC.substring(RFC.indexOf("*")+1)); 
      } 


     }catch(Exception _Exc) 
     { 
      Parent.RemoveUserWhenException(socket);QuitConnection(); 
     } 
    } 
} 

客户端代码

class Client extends JFrame 
{ 
    ServerName="192.168.1.103"; 
    ServerPort=1436; 

Client() 
{ 
    socket = new Socket(ServerName,ServerPort); 
    SendGroupFileToServer(Filepath,SelectedGroup);  
} 

/*******Function To Send File To Server and receiving the file ***********/ 
protected void SendGroupFileToServer(String FileName, String ToGroup) 
{ 
try { 

dataoutputstream.writeBytes(FileName.concat("!").concat(ToUser)+"\r\n"); 
//send file to sever 
      File myFile = new File (FileName.substring(9)); 
      byte [] mybytearray = new byte [(int)myFile.length()]; 
      FileInputStream fis = new FileInputStream(myFile); 
      BufferedInputStream bis = new BufferedInputStream(fis); 
      bis.read(mybytearray,0,mybytearray.length); 
      OutputStream os = socket.getOutputStream(); 
      System.out.println("Sending..."); 
      os.write(mybytearray,0,mybytearray.length); 
      os.flush(); 
      os.close(); 
      System.out.println("File successfully Sended to server"); 
      }catch(IOException _IoExc) { QuitConnection(QUIT_TYPE_DEFAULT);} 


       try { 
      socket1 = new Socket(ServerName,ServerPort); //Creating new Socket          
      dataoutputstream = new DataOutputStream(socket1.getOutputStream()); 
      dataoutputstream.writeBytes("FILEGET"+FileName.concat("!").concat(ToGroup+"*"+UserName)+"\r\n"); //sending string to server   

    } catch (IOException e1) { 
     e1.printStackTrace(); 
    } 

    // receive file sended by server 
     byte [] mybytearray = new byte [filesize]; 
     InputStream is; 
    try { 
     is = socket1.getInputStream(); 

     FileOutputStream fos = new FileOutputStream(Filepath); 
     BufferedOutputStream bos = new BufferedOutputStream(fos); 
     int bytesRead = is.read(mybytearray,0,mybytearray.length); 
     current = bytesRead; //up to this working fine 

     do { 
      bytesRead =is.read(mybytearray, current, (mybytearray.length-current)); //not reading the file data sent by server just waiting and not go ahead 
      if(bytesRead >= 0) 
       current += bytesRead; 
     } while(bytesRead > -1); 

     bos.write(mybytearray,0,current); 
     bos.flush(); 
     bos.close(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    } 

}

+1

太多的代码阅读。太多的风格暴行。抱歉。 –

+0

好的...忘了代码。如果你有关于使用套接字或任何其他方式将文件从一个客户端传输到另一个客户端的任何想法,那么请告诉我.. – krushnakant

+0

什么是例外?顺便说一句http://sscce.org/ – r0ast3d

回答

3

这里有这么多的问题,这是很难知道从哪里开始。

  1. accept()循环的thread.sleep()简直是在浪费时间。除了可能限制客户被接受的速度以外,它没有任何用处。如果那不是你的意图,不要这样做。

  2. 当您发现异常时,您正在做的所有事情都是在不打印异常消息的情况下退出服务器。所以当出现问题时,就像它在这里一样,你不可能知道它是什么。不要这样做。

  3. readLine()在EOS处返回null,您必须在其上关闭套接字,停止读取并退出线程。你没有测试过,所以你忽略了所有这三个步骤。不要这样做。

  4. 您正在构建一个DataInputStream围绕BufferedInputStream供读取命令时使用,但您没有将它传递给处理这些命令的方法。你只是通过套接字。你因此失去了数据。不要这样做。程序的每个部分都必须使用相同的输入流或读卡器作为套接字。

  5. 您正在将整个文件读入内存。这(a)假定文件大小适合于int; (b)不能扩展到大文件; (c)浪费空间,并且(d)增加延迟。不要这样做。

  6. 您正在忽略read()到该缓冲区的结果并假设它已被填充。你不能那样做。下面显示了在Java中复制流的正确方法。这适用于任何大小的缓冲器,例如8192,用于输入任意长度,并且不要求您将整个输入缓冲到内存中。您可以在发送文件时在客户端和接收时在服务器上使用此循环。

    while ((count = in.read(buffer)) > 0) 
    { 
        out.write(buffer, 0, count); 
    } 
    
  7. 类似于上述(4),则直接使用了一段东西的BufferedOutputStream一个DataOutputStream类和插座输出流为他人。不要这样做。程序的所有部分必须与套接字相同的输出流或写入器。

  8. 您不需要在close()之前flush();它会自动发生。

  9. 由于某些原因发送文件后,您正在创建一个新的连接并发送另一个命令。事后你甚至没有关闭连接。服务器将没有简单的方法知道这个连接和这个命令引用刚刚在上面的代码中发送的文件。这也是多余的,因为收到最终的EOS告诉服务器文件已成功发送。不要这样做。如果您需要使用该文件发送更多信息,请在文件之前,在同一连接上先发送。

  10. 您引用的参考文献展示了许多上述问题。努力寻找一个有信誉的起点。

+2

+1勇敢尝试 –

+0

非常感谢您的回复... – krushnakant

+0

对不起,但我没有使用过的文件和套接字,所以请你简单地告诉我你的第三步(建议)。我不明白这一点。:( – krushnakant

0

这是解决方案。请将此逻辑应用于您的代码。

我能够发送文件从服务器到客户端和客户端到服务器。

检查以下代码以将文件从客户端发送到服务器。它运作良好。

如果您有任何问题,请告诉我。

服务器端代码:

public class ServerRecieveFile { 
public static void main(String[] args) throws IOException {// TODO Auto-enerated method stub int filesize=1022386; 
int bytesRead; int currentTot= ; 
ServerSocket serverSocket=new ServerSocket(15123); 
Socket socket=rverSocket.accept(); 
byte [] bytearray = new byte [filesize]; 
InputStream is=socket.getInputStream(); 
File copyFileName=new File("c:/Files Sockets/2.txt"); 
FileOutputStream fos = new FileOutputStream(copyFileName); 
BufferedOutputStream bos = new BufferedOutputStream(fos); 
bytesRead = is.read(bytearray,0,bytearray.length); 
currentTot = bytesRead; 
do { 
bytesRead =is.read(bytearray, currentTot, (bytearray.length-currentTot)); if(bytesRead >= 0) 
currentTot += bytesRead; 
} while(bytesRead > -1); 
bos.write(bytearray, 0 , currentTot); 
bos.flush(); 
bos.close(); 
socket.close(); 
} 
} 

客户端代码:

public class ClientSendFile { 
public static void main(String[] args) throws UnknownHostException, IOException {// TODO Auto-generated method stub 
Client client=new Client(); 
Socket socket = new Socket(InetAddress.getLocalHost(),15123); 
System.out.println("Accepted connection : " + socket); 
File transferFile = new File ("c:/Files Sockets/1.txt"); 
byte [] bytearray = new byte (int)transferFile.length()]; 
FileInputStream fin = new FileInputStream(transferFile); 
BufferedInputStream bin = new BufferedInputStream(fin); 
bin.read(bytearray,0,bytearray.length); 
OutputStream os = socket.getOutputStream(); 
System.out.println("Sending Files..."); 
os.write(bytearray,0,bytearray.length); 
os.flush(); 
socket.close(); 
System.out.println("File transfer complete"); 
} 
} 
+0

To Shanahul:原来的问题是要求客户端 - >服务器 - >客户端文件传输,并且可能在服务器端没有临时存储 – Saint

相关问题