2011-04-15 143 views
22

我使用套接字連接我的Android應用程序(客戶端)和Java後端服務器。從客戶端我想每次與服務器通信時發送兩個數據變量。使用套接字發送和接收數據

1)某些類型的郵件中(由用戶通過界面定義)的

2)消息(由用戶通過界面定義)

的語言我怎麼可能把這些使服務器將每個解釋爲一個單獨的實體?

在讀取服務器端的數據並做出合適的結論後,我想向客戶端返回一條消息。 (我想我會沒事的)

所以我的兩個問題是我如何確定發送的兩個字符串(客戶端到服務器)在客戶端是唯一的,我怎樣才能將這兩個字符串分開服務器端。 (我正在考慮一串字符串,但無法建立,如果這是可能的或適當的。)

我打算髮布一些代碼,但我不知道這將如何幫助。

回答

48

我假設你正在使用TCP套接字進行客戶端 - 服務器交互?一種將不同類型的數據發送到服務器並且能夠區分這兩種數據的方法是將第一個字節(或者如果有超過256種類型的消息)專用作某種標識符。如果第一個字節是一個,那麼它是消息A,如果2,然後它的消息B.一個簡單的方法來發送這個在插座是使用DataOutputStream/DataInputStream

客戶:

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(); 

服務器:

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(); 

顯然,您可以發送各種數據,而不僅僅是字節和字符串(UTF)。

+3

Thankyou,這讓我前往在正確的方向! – 2011-04-15 19:34:15

4

最簡單的方法是將你的套接字包裝在ObjectInput/OutputStreams中併發送序列化的java對象。您可以創建包含相關數據的類,然後您不必擔心處理二進制協議的細節。只要確保在寫入每個對象「消息」後刷新對象流。

+0

儘管事實上該消息是很久以前寫的,但我有一個問題,我該如何區分發送String消息還是元素列表?我發佈我的[問題](http://stackoverflow.com/questions/25699232/java-chat-sending-users-list-from-server-to-clients-and-update-it) – Nikolas 2014-09-06 13:26:13

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); 
    } 
    } 
}