2016-04-06 31 views
1

クライアントの種類はAndroidで、言語はJavaです。サーバーにjson文字列を送信

このクラスはサーバーに接続し、接続されたサーバーへの出力ストリームを取得します。このコードの

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

}

目的は、サーバーのユーザーの資格情報を送信することです。

このC#のサーバーで

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

    } 

ので、Androidのクライアントは、資格情報を送信しますが、SendToServerクラスが呼び出されたときに、クライアントがサーバーから切断します。

C#サーバーにJson文字列を送信して、フィールドに応じて文字列を読み取り、オブジェクトにシリアル化できるようにするにはどうすればよいですか。

+1

あなたのJavaコードは、私が知る限り、jsonオブジェクトにのみ書き込みます。ネットワーキングとは関係ありません。 – Rob

+1

@Robクライアントがサーバーに接続し、出力ストリームを受け取ることを示すコードをいくつか追加しました。出力ストリーム "write"メソッドは、 "SendToServer"クラスで使用されます。 – Moynul

答えて

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(); } 
     */ 
    } 
} 

は、それはあなたが行を読んでいるが、あなたが行を書いていないあなたに

+0

こんにちは、私はHTTPリクエストを見て、投稿して取得しました。しかし、私の理想的な計画はソケットを使用することです。私はWebサーバーを使いたくありません。クライアントにサーバーに接続するつもりです。 – Moynul

+0

http://www.jayrambhia.com/blog/android-wireless-connection-2/ あなたはそれを見ることができます! –

+0

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

0

に役立ちます願っています。送信されるメッセージに行終了記号を追加するか、write()の代わりにprintln()を使用してください。

関連する問題