2016-04-06 14 views
1

Mein Clienttyp ist Android und die Sprache ist Java.Sende JSON String an Server

Diese Klasse stellt eine Verbindung zum Server her und ruft den Ausgabestream zum verbundenen Server ab.

class ConnectToServer extends AsyncTask<Void, Void, Void> 
{ 

    @Override 
    protected Void doInBackground(Void... params) 
    { 
     try { 
      socket = new Socket(ip,port); 
      output = new DataOutputStream(socket.getOutputStream()); 
      Log.d(TAG, "Connected To Server!"); 

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

     return null; 
    } 
} 

class SendToServer extends AsyncTask<Void, Void, Void> 
{ 
    //Our Json object 
    JSONObject obj;// = new JSONObject(); 

    //this class is called when the login button is pressed, it sends the username and password as arguments 
    public SendToServer(String username, String password) 
    { 
     //instantiate the new object 
     obj = new JSONObject(); 

     try { 
      //create the first field Type 
      obj.put("Type", new Integer(1)); //Type is something our Server will switch against-Type 1 = login request 
      obj.put("username", username); //our server will get username 
      obj.put("password",password); //our server will get password 
     } catch (JSONException e) { 
      e.printStackTrace();  //if we get problems let the developer know 
     } 
    } 
    @Override 
    protected Void doInBackground(Void... params) 
    { 
     String jsonText = obj.toString();      //convert our json object into a string 
     byte[] b =jsonText.getBytes(Charset.forName("UTF-8")); //convert our json object into a byte array 
     try { 
      output.writeInt(b.length); // write length of the message 
      output.write(b);   // write the message 
      output.flush();   //flush - empties the pipe 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 

     return null; 
    } 
} 

}

Der Zweck dieses Codes ist der Server die Benutzer-Anmeldeinformationen zu senden.

In diesem C# Server

private void serverClient() 
    { 
     while(true) 
     { 
      int len = ns.ReadByte(); //read how much data 

      if (len == 0) //if this == 0 this means client has quit the program 
       break;  //break out of loop and remove client from array list 

      if (len > 0) //we have a message 
      { 
       //read mess 
       byte[] message = new byte[len];   //create byte array 
       ns.Read(message, 0, message.Length); //read into the message byte array 
       string text = Encoding.ASCII.GetString(message, 0, len); 
       string text1 = Encoding.UTF8.GetString(message, 0, len); //build string from byte array up to how much data we got. 

       Console.WriteLine(text1); 
      } 
     } 

     removeClients(); 

    } 

So wird das Android-Client der Anmeldeinformationen senden, aber wenn die SendToServer Klasse aufgerufen wird, trennt der Client vom Server.

Wie kann ich eine JSON-Zeichenfolge an meinen C# -Server senden, damit sie die Zeichenfolge lesen und in ein Objekt serialisieren kann, abhängig von den Feldern.

+1

Ihr Java-Code, soweit ich das beurteilen kann, schreibt nur auf ein JSON-Objekt - nichts mit Vernetzung zu tun. – Rob

+1

@Rob Ich habe Code hinzugefügt, der zeigt, dass der Client eine Verbindung zum Server herstellt und den Ausgabestream empfängt. Die Schreibmethode des Ausgabestroms wird dann in der Klasse "SendToServer" verwendet. – Moynul

Antwort

1
private void updateDataToServer() { 

    ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); 
    nameValuePairs.add(new BasicNameValuePair("name", name)); 
    nameValuePairs.add(new BasicNameValuePair("score", score)); 

    try { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url_update); 
     httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
     HttpResponse response = httpclient.execute(httppost); 
     HttpEntity entity = response.getEntity(); 
     is = entity.getContent(); 
     Log.e("pass 1", "connection success "); 
    } catch (Exception e) { 
     Log.e("Fail 1", e.toString()); 
     Toast.makeText(getApplicationContext(), "Invalid IP Address", Toast.LENGTH_LONG).show(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
     } 
     is.close(); 
     result = sb.toString(); 
     Log.e("pass 2", "connection success "); 
    } catch (Exception e) { 
     Log.e("Fail 2", e.toString()); 
    } 

    try { 
     JSONObject json_data = new JSONObject(result); 
     code = (json_data.getInt("code")); 

     if (code == 1) { 
      /* 
      * Toast.makeText(getBaseContext(), "Update Successfully", 
      * Toast.LENGTH_SHORT).show(); 
      */ 
     } else { 
      Toast.makeText(getBaseContext(), "Sorry, Try Again", Toast.LENGTH_LONG).show(); 
     } 
    } catch (Exception e) { 
     Log.e("Fail 3", e.toString()); 
    } 

} 

class PostDataToServer extends AsyncTask<String, String, String> { 
    @Override 
    protected void onPreExecute() { 
     super.onPreExecute(); 
     /* 
     * pDialog = new ProgressDialog(MainActivity.this); 
     * pDialog.setMessage("Please wait..."); pDialog.show(); 
     */ 
    } 

    @Override 
    protected String doInBackground(String... params) { 
     HttpClient httpclient = new DefaultHttpClient(); 
     HttpPost httppost = new HttpPost(url_create_product); 

     try { 
      name = edt_name.getText().toString(); 
      score = edt_score.getText().toString(); 
      quocgia = edt_quocgia.getText().toString(); 
      // Add your data 
      List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); 
      nameValuePairs.add(new BasicNameValuePair("name", name)); 
      nameValuePairs.add(new BasicNameValuePair("score", score)); 
      nameValuePairs.add(new BasicNameValuePair("quocgia", quocgia)); 
      httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 

      // Execute HTTP Post Request 
      HttpResponse response = httpclient.execute(httppost); 

     } catch (ClientProtocolException e) { 
      // TODO Auto-generated catch block 
     } catch (IOException e) { 
      // TODO Auto-generated catch block 
     } 
     return null; 
    } 

    @Override 
    protected void onPostExecute(String s) { 
     /* 
     * if (pDialog.isShowing()) { pDialog.dismiss(); 
     * Toast.makeText(getApplication(), "Complete", 
     * Toast.LENGTH_LONG).show(); } 
     */ 
    } 
} 

Hoffe, es hilft Ihnen

+0

Hallo, ich habe HTTP-Anfragen angeschaut, geposted und bekommen. Aber mein idealer Plan ist, Sockets zu verwenden. Ich möchte keinen Webserver verwenden. Ich beabsichtige, dass mein Client eine Verbindung zu einem Server herstellt. – Moynul

+0

http://www.jayrambhia.com/blog/android-wireless-connection-2/ Sie können es sehen !! –

+0

http://docs.oracle.com/javase/tutorial/networking/sockets/readingWriting.html –

0

Sie lesen Linien, aber sie sind nicht Zeilen zu schreiben. Fügen Sie der gesendeten Nachricht einen Zeilenabschluss hinzu, oder verwenden Sie println() anstelle von write().

Verwandte Themen