I decided to add the ability to play over a local WiFi network into one of my applications. Immediately went to google client / server sockets. One device that the server distributes Wifi, and the second connects to this network. But the problem is that the server does not see what the client sends to it. If both the server and the client are started in one device, then everything works. How to make the server visible on this network? How can the client find the server's IP and connect to it? Here is the code:

Server.java:

import android.os.Handler; import android.widget.TextView; import android.widget.Toast; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class Server { MainActivity activity; private ServerSocket serverSocket; Handler updateConversationHandler; Thread serverThread = null; private TextView text; public static final int SERVERPORT = 5000; public Server(MainActivity activity) { this.activity = activity; this.text = activity.msg; } public void start() { updateConversationHandler = new Handler(); this.serverThread = new Thread(new ServerThread()); this.serverThread.start(); } public void stop() { try { if (!serverSocket.isClosed()) serverSocket.close(); } catch (IOException e) { e.printStackTrace(); } } class ServerThread implements Runnable { public void run() { Socket socket = null; try { serverSocket = new ServerSocket(SERVERPORT); } catch (IOException e) { e.printStackTrace(); } while (!Thread.currentThread().isInterrupted()) { try { socket = serverSocket.accept(); final String adress = socket.toString(); activity.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(activity, adress, Toast.LENGTH_SHORT).show(); } }); CommunicationThread commThread = new CommunicationThread(socket); new Thread(commThread).start(); } catch (IOException e) { e.printStackTrace(); } } } } class CommunicationThread implements Runnable { private Socket clientSocket; private BufferedReader input; public CommunicationThread(Socket clientSocket) { this.clientSocket = clientSocket; try { this.input = new BufferedReader(new InputStreamReader(this.clientSocket.getInputStream())); } catch (IOException e) { e.printStackTrace(); } } public void run() { while (!Thread.currentThread().isInterrupted()) { try { String read = input.readLine(); updateConversationHandler.post(new updateUIThread(read)); } catch (IOException e) { e.printStackTrace(); } } } } class updateUIThread implements Runnable { private String msg; public updateUIThread(String str) { this.msg = str; } @Override public void run() { text.setText(text.getText().toString() + "Client Says: " + msg + "\n"); } } } 

Client.java:

 import java.io.BufferedWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.InetAddress; import java.net.Socket; import java.net.UnknownHostException; public class Client { private Socket socket; private MainActivity activity; private static final int SERVERPORT = 5000; private static final String SERVER_IP = "10.0.2.2"; public Client(MainActivity activity) { this.activity = activity; } public void start() { new Thread(new ClientThread()).start(); } public void onClick() { try { String str = activity.edit.getText().toString(); PrintWriter out = new PrintWriter(new BufferedWriter( new OutputStreamWriter(socket.getOutputStream())), true); out.println(str); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (Exception e) { e.printStackTrace(); } } class ClientThread implements Runnable { @Override public void run() { try { InetAddress serverAddr = InetAddress.getByName(SERVER_IP); socket = new Socket(serverAddr, SERVERPORT); } catch (UnknownHostException e1) { e1.printStackTrace(); } catch (IOException e1) { e1.printStackTrace(); } } } public void stop() { if (!socket.isClosed()) { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } 

    1 answer 1

    I found a solution to my problem here .

    This issue can be solved using the JmDNS library

    Like so

     import android.content.Context; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; import android.util.Log; import java.io.IOException; import java.net.InetAddress; import javax.jmdns.JmDNS; import javax.jmdns.ServiceEvent; import javax.jmdns.ServiceInfo; import javax.jmdns.ServiceListener; /** * @author alwx * @version 1.0 */ public class NetworkDiscovery { private final String DEBUG_TAG = NetworkDiscovery.class.getName(); private final String TYPE = "_alwx._tcp.local."; private final String SERVICE_NAME = "LocalCommunication"; private Context mContext; private JmDNS mJmDNS; private ServiceInfo mServiceInfo; private ServiceListener mServiceListener; private WifiManager.MulticastLock mMulticastLock; public NetworkDiscovery(Context context) { mContext = context; try { WifiManager wifi = (WifiManager) mContext.getSystemService(android.content.Context.WIFI_SERVICE); WifiInfo wifiInfo = wifi.getConnectionInfo(); int intaddr = wifiInfo.getIpAddress(); byte[] byteaddr = new byte[]{ (byte) (intaddr & 0xff), (byte) (intaddr >> 8 & 0xff), (byte) (intaddr >> 16 & 0xff), (byte) (intaddr >> 24 & 0xff) }; InetAddress addr = InetAddress.getByAddress(byteaddr); mJmDNS = JmDNS.create(addr); } catch (IOException e) { Log.d(DEBUG_TAG, "Error in JmDNS creation: " + e); } } /** * starts server with defined names on given port * * @param port server port */ public void startServer(int port) { try { wifiLock(); mServiceInfo = ServiceInfo.create(TYPE, SERVICE_NAME, port, SERVICE_NAME); mJmDNS.registerService(mServiceInfo); } catch (IOException e) { Log.d(DEBUG_TAG, "Error in JmDNS initialization: " + e); } } /** * performs servers discovery * * @param listener listener, that will be called after successful discovery * (see {@link me.alwx.localcommunication.connection.NetworkDiscovery.OnFoundListener} */ public void findServers(final OnFoundListener listener) { mJmDNS.addServiceListener(TYPE, mServiceListener = new ServiceListener() { @Override public void serviceAdded(ServiceEvent serviceEvent) { ServiceInfo info = mJmDNS.getServiceInfo(serviceEvent.getType(), serviceEvent.getName()); listener.onFound(info); } @Override public void serviceRemoved(ServiceEvent serviceEvent) { } @Override public void serviceResolved(ServiceEvent serviceEvent) { mJmDNS.requestServiceInfo(serviceEvent.getType(), serviceEvent.getName(), 1); } }); } /** * closes connection & unregisters all services */ public void reset() { if (mJmDNS != null) { if (mServiceListener != null) { mJmDNS.removeServiceListener(TYPE, mServiceListener); mServiceListener = null; } mJmDNS.unregisterAllServices(); } if (mMulticastLock != null && mMulticastLock.isHeld()) { mMulticastLock.release(); } } /** * accuires Wi-Fi lock */ private void wifiLock() { WifiManager wifiManager = (WifiManager) mContext.getSystemService(android.content.Context.WIFI_SERVICE); mMulticastLock = wifiManager.createMulticastLock(SERVICE_NAME); mMulticastLock.setReferenceCounted(true); mMulticastLock.acquire(); } public interface OnFoundListener { void onFound(ServiceInfo info); } }