2016-01-28 3 views
0

Мы разрабатываем приложение для Android. В основном это взаимодействие с клиентским сервером. Клиентом является Android-телефон и сервер. Java.Client и серверная связь имеет место. Ожидается, что клиент отправит сообщение на сервер и сервер отвечает клиенту. Но на самом деле клиент может отправить сообщение на сервер, но сервер не может или отправляет неверный ответ. Я не понимаю, почему это происходит. Вот код клиента (Android):android client-java server communication

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Button; 
import android.widget.EditText; 
import android.os.AsyncTask; 
import android.widget.TextView; 

import java.io.BufferedReader; 
import java.io.DataInputStream; 
import java.io.DataOutputStream; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.io.PrintWriter; 
import java.net.InetAddress; 
import java.net.Socket; 
import java.net.UnknownHostException; 


public class MainActivity extends Activity { 
private Socket client; 
private PrintWriter printwriter; 
private EditText textField; 
public TextView accept; 
private Button button; 
private String message; 
private static BufferedReader bufferedReader; 
public static InputStreamReader inputStreamReader; 
String response; 
DataInputStream dis; 
static String Extra_message = "hkrw.clientside"; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    textField = (EditText) findViewById(R.id.editText1); 
    button = (Button) findViewById(R.id.button1); 
    this.accept = (TextView) findViewById(R.id.accept); 


    button.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View v) { 
      message = textField.getText().toString(); 
      textField.setText(""); 
      SendMessage sendMessageTask = new SendMessage(); 
      sendMessageTask.execute(); 
      accept.setText(response); 
     } 
    }); 
} 

private class SendMessage extends AsyncTask<Void, Void, Void> { 
    @Override 
    protected Void doInBackground(Void... params) { 
     DataOutputStream dataOutputStream = null; 
     DataInputStream smalldataInputStream = null; 
     try { 
      client = new Socket("192.168.1.6", 4446); 
      printwriter = new PrintWriter(client.getOutputStream(), true); 
      inputStreamReader = new InputStreamReader(client.getInputStream()); 
      bufferedReader = new BufferedReader(inputStreamReader); 
      printwriter.write(message); 
      // smalldataInputStream = new DataInputStream(client.getInputStream()); 

      printwriter.flush(); 
      printwriter.close(); 
      //dis= new DataInputStream(client.getInputStream()); 
      //response=dis.readUTF(); 
      response = bufferedReader.toString(); 
      client.getInputStream(); 

      // client.shutdownInput(); 
      // client.shutdownOutput(); 
      client.close(); 

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

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

     return null; 
    } 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_main, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

     return super.onOptionsItemSelected(item); 
    } 
} 

Вот код новой деятельности, которую я создал в стороне клиента.

import android.app.Activity; 
import android.content.Intent; 
import android.os.Bundle; 
import android.view.Menu; 
import android.view.MenuItem; 
import android.widget.TextView; 


public class respond extends Activity { 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_respond); 
    Intent intent=getIntent(); 
    String message = intent.getStringExtra(MainActivity.Extra_message); 
    TextView response; 
    response= (TextView) findViewById(R.id.textView1); 
    response.setText(message); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu; this adds items to the action bar if it is present. 
    getMenuInflater().inflate(R.menu.menu_respond, menu); 
    return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle action bar item clicks here. The action bar will 
    // automatically handle clicks on the Home/Up button, so long 
    // as you specify a parent activity in AndroidManifest.xml. 
    int id = item.getItemId(); 

    //noinspection SimplifiableIfStatement 
    if (id == R.id.action_settings) { 
     return true; 
    } 

     return super.onOptionsItemSelected(item); 
    } 
} 

Вот код сервера в Java:

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 
import java.net.ServerSocket; 
import java.net.Socket; 
import java.io.PrintWriter; 
import java.io.OutputStreamWriter; 
import java.io.FileOutputStream; 
import java.io.DataOutputStream; 





public class Server { 

private static ServerSocket serverSocket; 
private static Socket clientSocket; 
private static InputStreamReader inputStreamReader; 
private static BufferedReader bufferedReader; 
private static String message; 
    private static PrintWriter printwriter ; 
    static DataOutputStream dos; 


    public static void main(String[] args) { 
     String w="Hello World"; 


     try { 
     serverSocket = new ServerSocket(4446); // Server socket 

    } catch (IOException e) { 
     System.out.println("Could not listen on port: 4444"); 
    } 

    System.out.println("Server started. Listening to the port 4446"); 

    while (true) { 
     try { 

      clientSocket = serverSocket.accept(); // accept the client connection 
      inputStreamReader = new InputStreamReader(clientSocket.getInputStream()); 
      bufferedReader = new BufferedReader(inputStreamReader); // get the client message 
      message = bufferedReader.readLine(); 

      System.out.println(message); 



          dos=new DataOutputStream(clientSocket.getOutputStream()); 

          dos.writeUTF(w); 
          clientSocket.close(); 
          System.out.println(dos); 


          inputStreamReader.close(); 



     } catch (IOException ex) { 
      System.out.println("Problem in message reading"); 
     } 
    } 

      } 

} 
+0

Что такое ввод и какой результат был получен как неправильный? – prabindh

+0

Я загружу скриншоты – parth

+0

Любое сообщение от сервера к клиенту, а затем сервер отвечает сообщением cient – parth

ответ

2

этот пример посылает сообщение на сервер (ПК в БЛС), , а затем получает сообщение обратно от сервера к телефону, изменение текста соответственно.

изменить IP-адрес сервера на адрес компьютера в сети WLAN убедитесь запустить сервер, а затем телефон приложение, находясь в этом БЛС

Сервер:

public class ChatServer implements Runnable{ 

private Socket socket = null; 
private ServerSocket server = null; 
private Thread  thread = null; 

private DataInputStream streamIn = null; 
private DataOutputStream streamOut = null; 


int port; 
boolean done ; 

public ChatServer(){ 
    port = 6668; 
    try{ 
     System.out.println("Gewählter Port: " + port + ", bitte warte..."); 
     server = new ServerSocket(port); 
     System.out.println("Server gestartet: " + server); 
     start(); 
    } 
    catch(IOException ioe) 
    { 
     System.out.println(ioe); 
    } 
} 
public void start(){ 
    if (thread == null){ 
     thread = new Thread(this); 
     thread.start(); 
    } 
} 

public void run(){ 
    while (thread != null){ 
     try{ 
      System.out.println("waiting for Client ..."); 
      socket = server.accept(); 
      System.out.println("Client accepted: " + socket + " IP: "+ socket.getInetAddress()); 
      System.out.println("connecting ..."); 
      open(); 
      done = false; 

      while (!done){ 
       try{ 
        String line = streamIn.readUTF(); 
        System.out.println(line); 
        send("Server recieved :"+line); 
        done = line.equals(".bye"); 
       } 
       catch(IOException ioe){ 
        done = true; 
        ioe.printStackTrace(); 
       } 
      } 
      close(); 
     } 
     catch(IOException ie){ 
      System.out.println("Acceptance Error: " + ie); 
     } 
    } 
} 
public void send(String msg) 
{ 
    try 
    { 
     if(msg != null) { 
      streamOut.writeUTF(msg); 
      streamOut.flush(); 
     } 
    } 
    catch(IOException ioe) 
    { 
     ioe.printStackTrace(); 
    } 
} 
public void open() throws IOException{ 
    streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream())); 
    streamOut = new DataOutputStream(socket.getOutputStream()); 
} 
public void close() throws IOException{ 
    if (socket != null) socket.close(); 
    if (streamIn != null) streamIn.close(); 
    if (streamOut != null) streamOut.close(); 

} 
@SuppressWarnings("deprecation") 
public void stop(){ 
    if (thread != null){ 
     thread.stop(); 
     thread = null; 
    } 
} 


} 

клиент:

public class MainActivity extends Activity implements Runnable{ 

EditText textUnten; 
Button button; 
ChatProzKlasse chat; 
public static String puffer; 
public static String messages; 
public static TextView textMitte; 
Thread thread; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    textMitte = (TextView) findViewById (R.id.textMitteID); 
    textUnten = (EditText) findViewById (R.id.textUntenID); 
    button = (Button) findViewById(R.id.sendButton); 

    messages = ""; 



    chat = new ChatProzKlasse(); 
    thread = new Thread(this); 

    button.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      chat.client.send(textUnten.getText().toString()); 
      textUnten.setText(""); 



     } 
    }); 
    thread.start(); 


} 

public void setTextMitte(){ 
    runOnUiThread(new Runnable() { 
     @Override 
     public void run() { 
      textMitte.setText(messages); 
     } 
     }); 


} 
@Override 
protected void onResume() { 
    super.onResume(); 



} 

@Override 
public void run() { 
    while(true) { 
     setTextMitte(); 
     try { 
      thread.sleep(1000); 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
} 


} 
public class ChatClient { 

private Socket socket    = null; 

private DataInputStream console = null; 
private DataOutputStream streamOut = null; 
private DataInputStream streamIn = null; 
public static boolean isconnected = false; 

public ChatClient(String serverName, int serverPort){ 
    System.out.println("Verbindungsaufbau. Bitte warten ..."); 
    try{ 
     socket = new Socket(serverName, serverPort); 
     Log.d("DEBUG", "Connected: " + socket); 
     if(socket != null) { 
      start(); 
     } 
    } 
    catch(UnknownHostException uhe){ 
     Log.d("DEBUG","Host unknown: " + uhe.getMessage()); 
    } 
    catch(IOException ioe){ 
     Log.d("DEBUG","Unexpected exception: " + ioe.getMessage()); 
    } 

} 

public void start() throws IOException 
{ 
    console = new DataInputStream(System.in); 
    streamOut = new DataOutputStream(socket.getOutputStream()); 
    isconnected = true; 

} 

public void stop(){ 
    try{ 
     if (console != null) console.close(); 
     if (streamOut != null) streamOut.close(); 
     if (socket != null) socket.close(); 
    } 
    catch(IOException ioe){ 
     System.out.println("Error closing ..."); 
    } 
} 
public void open() throws IOException{ 
    streamIn = new DataInputStream(new BufferedInputStream(socket.getInputStream())); 
} 
public void close() throws IOException{ 
    if (socket != null) socket.close(); 
    if (console != null) console.close(); 
} 

public void send(String msg) 
{ 
    try 
    { 
     if(msg != null) { 
      streamOut.writeUTF(msg); 
      streamOut.flush(); 
     } 
    } 
    catch(IOException ioe) 
    { 
     Log.d("DEBUG","Sending error: " + ioe.getMessage()); 
    } 
} 

public void recieve(){ 
    try{ 
     open(); 
     boolean done = false; 

     while (!done){ 
      try{ 
       String line = streamIn.readUTF(); 
       if(!(line.equals(""))) { 
        MainActivity.messages =line; 
        MainActivity.puffer = line; 
       } 
       System.out.println(" " + line); 
       done = line.equals(".bye"); 
      } 
      catch(IOException ioe){ 
       done = true; 
       ioe.printStackTrace(); 
      } 
     } 
     close(); 
    } 
    catch(IOException ie){ 
     System.out.println("Acceptance Error: " + ie); 
    } 
} 



} 



public class ChatProzKlasse implements Runnable { 
Thread thread; 
ChatClient client; 

public ChatProzKlasse(){ 
    thread = new Thread(this); 
    thread.start(); 

} 

@Override 
public synchronized void run() { 

    if(client == null) { 
     try { 
      System.out.println(" trying new Client"); 
      client = new ChatClient("192.168.1.111", 6668); 


     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
    if (client !=null){ 
     if(client != null && ChatClient.isconnected) { 
      client.recieve(); 
     } 
    } 

}} 
+0

Спасибо. Я исполню код. – parth

+0

клиент состоит из 3 отдельных классов, которые я просто поместил в них внизу, не забудьте также запустить новый Chatserver() на main (string [] args) – railwanderer

+0

это вам помогло? – railwanderer