2013-03-03 207 views
0

我創建了一個TCP服務器(PC) - 客戶端(Android)應用程序。我將客戶端連接到服務器,但是當我重新啓動我的android應用程序時,我無法建立連接。如何處理這個,所以當我重新啓動android應用程序,它連接到服務器的端口? 服務器是VB.net和Android的Android TCP服務器客戶端

Sub Main() 
    Dim serverSocket As New TcpListener(8888) 
    Dim requestCount As Integer 
    Dim clientSocket As TcpClient 
    serverSocket.Start() 
    msg("Server Started") 
    clientSocket = serverSocket.AcceptTcpClient() 
    msg("Accept connection from client") 
    requestCount = 0 
    Dim flag As Boolean = True 

    While (flag = True) 
     Try 
      requestCount = requestCount + 1 
      Dim networkStream As NetworkStream = _ 
        clientSocket.GetStream() 
      Dim bytesFrom(10024) As Byte 
      networkStream.Read(bytesFrom, 0, CInt(clientSocket.ReceiveBufferSize)) 
      Dim dataFromClient As String = _ 
        System.Text.Encoding.ASCII.GetString(bytesFrom) 
      msg("Data from client - " + dataFromClient) 
      Dim serverResponse As String = _ 
       "Server response " + Convert.ToString(requestCount) 
      Dim sendBytes As [Byte]() = _ 
       Encoding.ASCII.GetBytes(serverResponse) 
      networkStream.Write(sendBytes, 0, sendBytes.Length) 
      networkStream.Flush() 
      msg(serverResponse) 
     Catch ex As Exception 
      MsgBox(ex.ToString) 
     End Try 
    End While 

    clientSocket.Close() 
    serverSocket.Stop() 
    msg("exit") 
    Console.ReadLine() 
End Sub 

Sub msg(ByVal mesg As String) 
    mesg.Trim() 
    Console.WriteLine(" >> " + mesg) 
End Sub 

public class connectTask extends AsyncTask<String, String, TCPClient> { 

    @Override 
    protected TCPClient doInBackground(String... message) { 

     // we create a TCPClient object and 
     mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() { 
      @Override 
      // here the messageReceived method is implemented 
      public void messageReceived(String message) { 
       // this method calls the onProgressUpdate 
       publishProgress(message); 
      } 
     }); 
     mTcpClient.run(); 
     return null; 
    } 

public class TCPClient { 
private String serverMessage; 
public static final String SERVERIP = "192.168.1.65"; //your computer IP address 
public static final int SERVERPORT = 4444; 
private OnMessageReceived mMessageListener = null; 
private boolean mRun = false; 

PrintWriter out; 
BufferedReader in; 

/** 
* Constructor of the class. OnMessagedReceived listens for the messages received from server 
*/ 
public TCPClient(OnMessageReceived listener) { 
    mMessageListener = listener; 
} 

/** 
* Sends the message entered by client to the server 
* @param message text entered by client 
*/ 
public void sendMessage(String message){ 
    if (out != null && !out.checkError()) { 
     out.println(message); 
     out.flush(); 
    } 
} 

public void stopClient(){ 
    mRun = false; 
} 

public void run() { 

    mRun = true; 

    try { 
     //here you must put your computer's IP address. 
     InetAddress serverAddr = InetAddress.getByName(SERVERIP); 

     Log.e("TCP Client", "C: Connecting..."); 

     //create a socket to make the connection with the server 
     Socket socket = new Socket(serverAddr, SERVERPORT); 

     try { 

      //send the message to the server 
      out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true); 

      Log.e("TCP Client", "C: Sent."); 

      //receive the message which the server sends back 
      in = new BufferedReader(new InputStreamReader(socket.getInputStream())); 

      //in this while the client listens for the messages sent by the server 
      while (mRun) { 
       serverMessage = in.readLine(); 

       if (serverMessage != null && mMessageListener != null) { 
        //call the method messageReceived from MyActivity class 
        mMessageListener.messageReceived(serverMessage); 
       } 
       serverMessage = null; 

      } 


      Log.e("RESPONSE FROM SERVER", "S: Received Message: '" + serverMessage + "'"); 


     } catch (Exception e) { 

      Log.e("TCP", "S: Error", e); 

     } finally { 
      //the socket must be closed. It is not possible to reconnect to this socket 
      // after it is closed, which means a new socket instance has to be created. 
      socket.close(); 
      Log.e("Socket","Closed"); 
     } 

    } catch (Exception e) { 

     Log.e("TCP", "C: Error", e); 

    } 

} 
+1

請張貼一些代碼,還有你得到的任何錯誤? – conor 2013-03-03 11:25:53

回答

3

TCP客戶端的Java可能是最常用的協議,只是因爲它是用於許多應用,如HTTP,POP,SMTP,TCP等是協議這可以確保接收方能夠準確接收發件人發送的內容 - 不會有錯誤,它將按照正確的順序進行,一切都會正常工作。

try { 
     Socket s = new Socket("http://helloandroid.com&quot",80); 
} catch (UnknownHostException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
} catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
} 

這是一個簡單的客戶端TCP請求。如果連接成功建立,您可以獲得所需的通信流程。

現在讓我們來看看服務器端的例子:

try { 
    Boolean end = false; 
    ServerSocket ss = new ServerSocket(12345); 
    while(!end){ 
      //Server is waiting for client here, if needed 
      Socket s = ss.accept(); 
      BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream())); 
      PrintWriter output = new PrintWriter(s.getOutputStream(),true); //Autoflush 
      String st = input.readLine(); 
      Log.d("Tcp Example", "From client: "+st); 
      output.println("Good bye and thanks for all the fish :)"); 
      s.close(); 
      if (STOPPING conditions){ end = true; } 
    } 
ss.close(); 


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

末見客戶端:

try { 
    Socket s = new Socket("localhost",12345); 

    //outgoing stream redirect to socket 
    OutputStream out = s.getOutputStream(); 

    PrintWriter output = new PrintWriter(out); 
    output.println("Hello Android!"); 
    BufferedReader input = new BufferedReader(new InputStreamReader(s.getInputStream())); 

    //read line(s) 
    String st = input.readLine(); 
    . . . 
    //Close connection 
    s.close(); 


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

就是這樣。希望你發現這會有幫助。