How to connect two Android devices via a socket without a server

I am trying to develop an Android application that can exchange peer-to-peer data with other devices without a server. So please suggest how I can do this. Thank you in advance.

+6
source share
4 answers

Java provides ServerSocket and Socket for connecting b / w devices. One of the devices that you can do as a server and another device that you can do as a client and exchange data without entering a server hosted on any machine.

Another and best option is to use Wi-Fi Peer-to-Peer . WifiP2pManager helps you achieve your goal. Here is an example.

+3
source

This is the complete chat code using SocketProgramming without a server.

In my application, you are a client first and you are looking for a server. When you do not find any server, you become a server and wait for the client.

public class MainActivity extends ActionBarActivity { private Handler handler = new Handler(); private TextView text; private EditText input; private Button send; private Socket socket; private DataOutputStream outputStream; private BufferedReader inputStream; private String DeviceName = "Device"; private boolean searchNetwork() { log("Connecting"); String range = "192.168.56."; for (int i = 1; i <= 255; i++) { String ip = range + i; try { socket = new Socket(); socket.connect(new InetSocketAddress(ip, 9000), 50); outputStream = new DataOutputStream(socket.getOutputStream()); inputStream = new BufferedReader(new InputStreamReader( socket.getInputStream())); DeviceName += "1"; Log.i("Server", DeviceName); log("Connected"); return true; } catch (Exception e) { } } return false; } private void runNewChatServer() { ServerSocket serverSocket; try { serverSocket = new ServerSocket(9000); log("Waiting for client..."); socket = serverSocket.accept(); DeviceName += "2"; log("a new client Connected"); } catch (IOException e) { } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text = (TextView) findViewById(R.id.text); input = (EditText) findViewById(R.id.input); send = (Button) findViewById(R.id.send); Thread thread = new Thread(new Runnable() { @Override public void run() { try { if (!searchNetwork()) { runNewChatServer(); } outputStream = new DataOutputStream( socket.getOutputStream()); inputStream = new BufferedReader(new InputStreamReader( socket.getInputStream())); while (true) { String Message = inputStream.readLine(); if (Message != null) { log(Message); } } } catch (IOException e) { log("Error: IO Exception"); e.printStackTrace(); } } }); send.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { if (outputStream == null) { return; } try { String Message = input.getText().toString() + "\n"; outputStream.write(Message.getBytes()); log2(input.getText().toString()); } catch (IOException e) { e.printStackTrace(); } input.setText(""); } }); thread.start(); } private void log(final String message) { handler.post(new Runnable() { String DeviceName2=""; @Override public void run() { if (DeviceName.equals("Device1")) { DeviceName2 = "Device2"; }else if(DeviceName.equals("Device2")) { DeviceName2 = "Device1"; }else{ DeviceName2 = "UnknowDevice"; } text.setText(text.getText() + "\n" + DeviceName2 + " :" + message); } }); } private void log2(final String message) { handler.post(new Runnable() { @Override public void run() { text.setText(text.getText() + "\n" + "you" + " :" + message); } }); } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { if (socket != null) { try { socket.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.exit(0); return true; } return super.onKeyDown(keyCode, event); } } 
+3
source

If you are looking for such a P2P on a local network, there are two parts:

  • Peer detection
  • Communication with peers

Among the Android APIs, you can use the Network Services Discovery APIs for this or the Wifi P2P Service Discovery API .

There is a wrapper library that uses them internally and has relatively better documentation - Salut, which can also be used.

I also created a library for P2P - Near , which uses sockets directly. The problem I encountered with the Android API was that the discovery did not happen with certainty every time, and the main problem was unknown.

If you are looking for P2P over the Internet, socket IO is a common solution. Even Near should be able to facilitate the transfer if you provide IP addresses, and they are not behind NAT firewalls.

+1
source

Your project has a big problem: ...

If there is no central server, some Android devices should act as a client and others as a server, but in some situations this will not work:

  • When a mobile phone provider assigns a private and non-public IP address

  • When the device is connected to a Wi-Fi network, but the NAT rule is not defined on the router.

In both cases, the problem is that the listening port of the device, which should act as a server, is unavailable.

+1
source

Source: https://habr.com/ru/post/984042/


All Articles