2011-04-15 26 views
22

Estoy usando sockets para conectar mi aplicación Android (cliente) y un servidor back-end Java. Desde el cliente me gustaría enviar dos variables de datos cada vez que me comunico con el servidor.Usando sockets para enviar y recibir datos

1) algún tipo de mensaje (Definido por el usuario a través de la interfaz)

2) El idioma del mensaje (Definido por el usuario a través de la interfaz)

¿Cómo podría enviar a estos para que el servidor interpreta cada uno como una entidad separada?

Después de haber leído los datos del lado del servidor y llegado a una conclusión adecuada, me gustaría devolver un solo mensaje al cliente. (Creo que estaré bien con esto)

Así que mis dos preguntas son cómo puedo establecer que las dos cadenas que se envían (cliente a servidor) son únicas en el lado del cliente y cómo puedo separar estas dos cadenas en el lado del servidor. (Estaba pensando en un conjunto de cadenas, pero no pude establecer si esto era posible o apropiado.)

Iba a publicar algún código, pero no estoy seguro de cómo eso podría ayudar.

Respuesta

48

Supongo que está utilizando sockets TCP para la interacción cliente-servidor? Una forma de enviar diferentes tipos de datos al servidor y hacer que sea capaz de diferenciar entre los dos es dedicar el primer byte (o más si tiene más de 256 tipos de mensajes) como algún tipo de identificador. Si el primer byte es uno, entonces es el mensaje A, si es 2, entonces su mensaje B. Una forma fácil de enviar este sobre el zócalo es utilizar DataOutputStream/DataInputStream:

Cliente:

Socket socket = ...; // Create and connect the socket 
DataOutputStream dOut = new DataOutputStream(socket.getOutputStream()); 

// Send first message 
dOut.writeByte(1); 
dOut.writeUTF("This is the first type of message."); 
dOut.flush(); // Send off the data 

// Send the second message 
dOut.writeByte(2); 
dOut.writeUTF("This is the second type of message."); 
dOut.flush(); // Send off the data 

// Send the third message 
dOut.writeByte(3); 
dOut.writeUTF("This is the third type of message (Part 1)."); 
dOut.writeUTF("This is the third type of message (Part 2)."); 
dOut.flush(); // Send off the data 

// Send the exit message 
dOut.writeByte(-1); 
dOut.flush(); 

dOut.close(); 

servidor :

Socket socket = ... // Set up receive socket 
DataInputStream dIn = new DataInputStream(socket.getInputStream()); 

boolean done = false; 
while(!done) { 
    byte messageType = dIn.readByte(); 

    switch(messageType) 
    { 
    case 1: // Type A 
    System.out.println("Message A: " + dIn.readUTF()); 
    break; 
    case 2: // Type B 
    System.out.println("Message B: " + dIn.readUTF()); 
    break; 
    case 3: // Type C 
    System.out.println("Message C [1]: " + dIn.readUTF()); 
    System.out.println("Message C [2]: " + dIn.readUTF()); 
    break; 
    default: 
    done = true; 
    } 
} 

dIn.close(); 

Obviamente, puede enviar todo tipo de información, no sólo de bytes y cadenas (UTF).

+3

Gracias, esto me tiene partida ¡en la dirección correcta! –

+0

@ user671430 ¿Hay algo más que necesite para marcar esta pregunta como respondida? –

+0

Hola jugador, un pequeño problema. En el lado del servidor estoy usando un ServerSocket en lugar de solo Socket. DataInputStream no parece ser compatible en este caso. –

4

la manera más fácil de hacer esto es envolver sus sockets en ObjectInput/OutputStreams y enviar objetos java serializados. puede crear clases que contengan los datos relevantes, y luego no necesita preocuparse por los detalles esenciales de manejar protocolos binarios. solo asegúrate de enjuagar tus flujos de objetos después de escribir cada "mensaje" de objeto.

+0

a pesar de que el mensaje está escrito hace mucho tiempo, tengo una pregunta, ¿cómo puedo distinguir entre enviar un mensaje de cadena o una lista de elementos? Publiqué mi [pregunta] (http://stackoverflow.com/questions/25699232/java-chat-sending-users-list-from-server-to-clients-and-update-it) – Nikolas

2
//Client 

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

    public class Client { 
     public static void main(String[] args) { 

     String hostname = "localhost"; 
     int port = 6789; 

     // declaration section: 
     // clientSocket: our client socket 
     // os: output stream 
     // is: input stream 

      Socket clientSocket = null; 
      DataOutputStream os = null; 
      BufferedReader is = null; 

     // Initialization section: 
     // Try to open a socket on the given port 
     // Try to open input and output streams 

      try { 
       clientSocket = new Socket(hostname, port); 
       os = new DataOutputStream(clientSocket.getOutputStream()); 
       is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
      } catch (UnknownHostException e) { 
       System.err.println("Don't know about host: " + hostname); 
      } catch (IOException e) { 
       System.err.println("Couldn't get I/O for the connection to: " + hostname); 
      } 

     // If everything has been initialized then we want to write some data 
     // to the socket we have opened a connection to on the given port 

     if (clientSocket == null || os == null || is == null) { 
      System.err.println("Something is wrong. One variable is null."); 
      return; 
     } 

     try { 
      while (true) { 
      System.out.print("Enter an integer (0 to stop connection, -1 to stop server): "); 
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 
      String keyboardInput = br.readLine(); 
      os.writeBytes(keyboardInput + "\n"); 

      int n = Integer.parseInt(keyboardInput); 
      if (n == 0 || n == -1) { 
       break; 
      } 

      String responseLine = is.readLine(); 
      System.out.println("Server returns its square as: " + responseLine); 
      } 

      // clean up: 
      // close the output stream 
      // close the input stream 
      // close the socket 

      os.close(); 
      is.close(); 
      clientSocket.close(); 
     } catch (UnknownHostException e) { 
      System.err.println("Trying to connect to unknown host: " + e); 
     } catch (IOException e) { 
      System.err.println("IOException: " + e); 
     } 
     }   
    } 





//Server 




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

public class Server1 { 
    public static void main(String args[]) { 
    int port = 6789; 
    Server1 server = new Server1(port); 
    server.startServer(); 
    } 

    // declare a server socket and a client socket for the server 

    ServerSocket echoServer = null; 
    Socket clientSocket = null; 
    int port; 

    public Server1(int port) { 
    this.port = port; 
    } 

    public void stopServer() { 
    System.out.println("Server cleaning up."); 
    System.exit(0); 
    } 

    public void startServer() { 
    // Try to open a server socket on the given port 
    // Note that we can't choose a port less than 1024 if we are not 
    // privileged users (root) 

     try { 
     echoServer = new ServerSocket(port); 
     } 
     catch (IOException e) { 
     System.out.println(e); 
     } 

    System.out.println("Waiting for connections. Only one connection is allowed."); 

    // Create a socket object from the ServerSocket to listen and accept connections. 
    // Use Server1Connection to process the connection. 

    while (true) { 
     try { 
     clientSocket = echoServer.accept(); 
     Server1Connection oneconnection = new Server1Connection(clientSocket, this); 
     oneconnection.run(); 
     } 
     catch (IOException e) { 
     System.out.println(e); 
     } 
    } 
    } 
} 

class Server1Connection { 
    BufferedReader is; 
    PrintStream os; 
    Socket clientSocket; 
    Server1 server; 

    public Server1Connection(Socket clientSocket, Server1 server) { 
    this.clientSocket = clientSocket; 
    this.server = server; 
    System.out.println("Connection established with: " + clientSocket); 
    try { 
     is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); 
     os = new PrintStream(clientSocket.getOutputStream()); 
    } catch (IOException e) { 
     System.out.println(e); 
    } 
    } 

    public void run() { 
     String line; 
    try { 
     boolean serverStop = false; 

      while (true) { 
       line = is.readLine(); 
     System.out.println("Received " + line); 
       int n = Integer.parseInt(line); 
     if (n == -1) { 
      serverStop = true; 
      break; 
     } 
     if (n == 0) break; 
       os.println("" + n*n); 
      } 

     System.out.println("Connection closed."); 
      is.close(); 
      os.close(); 
      clientSocket.close(); 

     if (serverStop) server.stopServer(); 
    } catch (IOException e) { 
     System.out.println(e); 
    } 
    } 
} 
Cuestiones relacionadas