2011-01-12 15 views
10

Implemento el servidor TCP simple y las clases de cliente TCP que pueden enviar el mensaje del cliente al servidor y el mensaje se convertirá a mayúsculas en el servidor, pero ¿cómo puedo lograr transferir archivos de servidor a cliente y cargar archivos de cliente a servidor? los siguientes códigos son los que tengo.cómo implementar el servidor TCP y el cliente TCP en java para transferir archivos

TCPClient.java:

import java.io.*; 
import java.net.*; 

class TCPClient { 
public static void main(String args[]) throws Exception { 
     String sentence; 
     String modifiedSentence; 
     BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
     Socket clientSocket = new Socket("127.0.0.1", 6789); 
     DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
     BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     sentence = inFromUser.readLine(); 
     outToServer.writeBytes(sentence + "\n"); 
     modifiedSentence = inFromServer.readLine(); 
     System.out.println("FROM SERVER:" + modifiedSentence); 
     clientSocket.close(); 
    } 
} 

TCPServer.java:

import java.io.*; 
import java.net.*; 

class TCPServer { 
    public static void main(String args[]) throws Exception { 
     int firsttime = 1; 
     while (true) { 
      String clientSentence; 
      String capitalizedSentence=""; 
      ServerSocket welcomeSocket = new ServerSocket(3248); 
      Socket connectionSocket = welcomeSocket.accept(); 
      BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); 
      DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); 
      clientSentence = inFromClient.readLine(); 
      //System.out.println(clientSentence); 
      if (clientSentence.equals("set")) { 
       outToClient.writeBytes("connection is "); 
       System.out.println("running here"); 
       //welcomeSocket.close(); 
       //outToClient.writeBytes(capitalizedSentence); 
      } 
      capitalizedSentence = clientSentence.toUpperCase() + "\n"; 
      //if(!clientSentence.equals("quit")) 
      outToClient.writeBytes(capitalizedSentence+"enter the message or command: "); 
      System.out.println("passed"); 
      //outToClient.writeBytes("enter the message or command: "); 
      welcomeSocket.close(); 
      System.out.println("connection terminated"); 
     } 
    } 
} 

Así, el TCPServer.java se ejecutará en primer lugar, y luego ejecutar el TCPClient.java, y trato de usar la cláusula if en el TCPServer.java para poner a prueba cuál es la entrada del usuario, ahora realmente quiero implementar cómo transferir archivos desde ambos lados (descargar y subir) .Gracias.

+0

http://stackoverflow.com/questions/4687615/how-to-achieve-transfer-file-between-client-and- server-using-java-socket –

+0

Además de todas las respuestas, puede leer todos los bytes de cualquier archivo a la vez con [readAllBytes (...)] (http://docs.oracle.com/javase/8/docs/ api/java/nio/file/Files.html # readAllBytes-java.nio.file.Path-) y escríbalos en cualquier archivo w ith [write (...)] (http://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#write-java.nio.file.Path-byte: A-java.nio.file.OpenOption ...-). – thanopi57

Respuesta

2

This El enlace debería ser de ayuda.

+0

Agregué if (clientSentence.equals ("bueno")) \t {capitalizedSentence = "connection is set"; \t //outToClient.writeBytes(capitalizedSentence); \t} \t otro \t \t \t {capitalizedSentence = clientSentence.toUpperCase() + "\ n"; \t \t \t \t \t \t} outToClient.writeBytes (capitalizedSentence); welcomeSocket.close(); para el código del servidor, pero parece que no está funcionando, ¿me puede ayudar con eso, por favor? – starcaller

+0

Necesitará decirnos qué código está utilizando y qué excepción está recibiendo. – npinti

+0

He actualizado la pregunta, por favor échale un vistazo, gracias. – starcaller

1

Suponiendo que desea seguir apoyando el envío de mensajes, así como el envío de archivos de ida y vuelta ...

A medida que tenemos ahora, que está utilizando writeBytes para enviar datos desde el cliente al servidor.

Puede usarlo para enviar nada, al igual que el contenido de archivos ...

Pero tendrá que definir un protocolo entre el cliente y el servidor para que sepan cuando un archivo se transfiere en lugar de una mensaje de chat

Por ejemplo, podría enviar el mensaje/cadena "FILECOMING" antes de enviar un archivo al servidor y sabría esperar los bytes de un archivo. De manera similar, necesitaría una forma de marcar el final de un archivo también ...

Como alternativa, podría enviar un tipo de mensaje antes de cada mensaje.

Una solución más eficaz/receptiva es hacer la transferencia de archivos en un subproceso/subproceso independiente, esto significa que los mensajes de chat no se detienen por las transferencias. Siempre que se requiera una transferencia de archivos, se crea una nueva conexión de hilo/socket solo para eso.

~ Chris

+0

¿me puede dar algunas muestras de código para estudiar, por favor, thx. – starcaller

+0

Lo ideal sería que necesitaras algunos para usar sockets separados para manejar los comandos. La forma en que se hace con FTP es que hay un canal de comando y un canal de datos. –

4

Así que vamos a asumir en el lado del servidor que ha recibido el nombre de archivo y la ruta del archivo. Este código debería darte una idea.

SERVIDOR

PrintStream out = new PrintStream(socket.getOutputStream(), true); 
FileInputStream requestedfile = new FileInputStream(completeFilePath); 
byte[] buffer = new byte[1]; 
out.println("Content-Length: "+new File(completeFilePath).length()); // for the client to receive file 
while((requestedfile.read(buffer)!=-1)){ 
    out.write(buffer); 
    out.flush();  
    out.close();  
} 
requestedfile.close(); 

CLIENTE

DataInputStream in = new DataInputStream(socket.getInputStream()); 
int size = Integer.parseInt(in.readLine().split(": ")[1]); 
byte[] item = new byte[size]; 
for(int i = 0; i < size; i++) 
    item[i] = in.readByte(); 
FileOutputStream requestedfile = new FileOutputStream(new File(fileName)); 
BufferedOutputStream bos = new BufferedOutputStream(requestedfile); 
bos.write(item); 
bos.close(); 
fos.close(); 
0
import java.io.*; 
import java.net.*; 

class TCPClient 
{ 
    public static void main(String argv[]) throws IOException 
    { 
     String sentence; 
     String modifiedSentence; 
     Socket clientSocket = new Socket("*localhost*", *portnum*); // new Socket("192.168.1.100", 80); 
     System.out.println("Enter your ASCII code here"); 
     BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
     sentence = inFromUser.readLine(); 
// System.out.println(sentence); 

      while(!(sentence.isEmpty())) 
      {   
       DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 
       outToServer.writeBytes(sentence); 

       BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
       modifiedSentence = inFromServer.readLine(); 

        while(!(modifiedSentence.isEmpty())) 
        {     
         System.out.println("FROM SERVER: " + modifiedSentence); 
         break; 
        } 

       System.out.println("Enter your ASCII code here"); 
       inFromUser = new BufferedReader(new InputStreamReader(System.in)); 
       sentence = inFromUser.readLine(); 
      } 

     System.out.println("socket connection going to be close");  
     clientSocket.close(); 
    } 

} 
Cuestiones relacionadas