So far, I managed to start the server on one Android device (wifi tethering / hotspot) and allow the client (another android) to connect and send messages to the server. Then the server responded to this. I understand that I need a way so that the server does not listen to clients, even if the chat application does not work. Clients should be able to send messages, and the server should receive this. Should I use Service or IntentService to archive this? I can not spread from AsyncTask and Service ... how to implement this? Some sample code would be great.
This is what my server looks like:
public class Server extends AsyncTask<Integer, Void, Socket> { private ServerSocket serverSocket; private TextView textView; private String incomingMsg; private String outgoingMsg; public Server(TextView textView) { this.textView = textView; } public void closeServer() { try { serverSocket.close(); } catch (IOException e) { Log.d("Server", "Closung the server caused a problem"); e.printStackTrace(); } } @Override protected Socket doInBackground(Integer... params) { try { serverSocket = new ServerSocket(params[0]);
And this is my client:
public class Client extends AsyncTask<Integer, Void, Socket> { private WifiManager wifi; private Context context; private String outMsg; private String inMsg; public Client(Context context, WifiManager wifiManager) { this.context = context; this.wifi = wifiManager; } @Override protected Socket doInBackground(Integer... params) { try { String gateway = intToIp(wifi.getDhcpInfo().gateway); Socket socket = new Socket(gateway, params[0]); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())); String ipAdress = intToIp(wifi.getConnectionInfo().getIpAddress()); outMsg = ", Client " + ipAdress +" is connecting!" + System.getProperty("line.separator"); out.write(outMsg); out.flush(); //accept server response inMsg = in.readLine() + System.getProperty("line.separator"); return socket; } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } public String intToIp(int addr) { return ((addr & 0xFF) + "." + ((addr >>>= 8) & 0xFF) + "." + ((addr >>>= 8) & 0xFF) + "." + ((addr >>>= 8) & 0xFF)); } protected void onPostExecute(Socket socket) { if(socket != null) { Log.i("Client", "Client sent: " + outMsg); Toast.makeText(context, "\nClient sent: " + outMsg + "\n", Toast.LENGTH_LONG).show(); Log.i("Client", "Client received: " + inMsg); Toast.makeText(context, "Client received: " + inMsg + "\n", Toast.LENGTH_LONG).show(); } else { Log.d("Client", "Can't connect to server!"); Toast.makeText(context, "Can't connect to server!", Toast.LENGTH_LONG).show(); } } }
How to make a service from a server? Should the Client be a Service?
source share