简体   繁体   中英

server and client chat over wifi in android devices.ex Samsung Duos, Galaxy

i am a new bee for android development, and i am planing for a chat application between 2 or more android devices like Samsung Duos or higher version, without using internet. and Only using WIFI. 1) is it possible? if yes then please suggest some code segments or links for establishing connection between 2 devices over WiFi and transfer text message between them.

You have to create the same APP for two devices using the chat.

In AndroidManifest.xml is useful to put:

<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Then in the MainActivity class and the other classes where data is transferred it's essential to put this:

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                                                .permitAll().build();
StrictMode.setThreadPolicy(policy);

This part of code able the device to send and receive data from external devices connected on the same WiFi network.

Ok, then you will have to create sockets. A socket permits you to send and receive data form particular IP and port. There you have a very simple example:

Socket client = new Socket("1.2.3.4", 2000); // This will connect to the other device
OutputStream out = client.getOutputStream(); //This will let you send data.
InputStream in = client.getInputStream(); //This will let you receive data.

Now if you can send and receive, there's a common question that I've ever seen resolved here...

What if you want to know if your friend have sent you data?

You need to create a BufferedReader :

 iBuff = new BufferedReader(new InputStreamReader(client.getInputStream()));

Then you are able to know if datas is available in the buffer:

while (iBuff.ready()) { //While there's data in buffer
            in.read(bytes, 0, 1); //Read
}

If you try to read with an empty buffer, it will get blocked. The same for input.available() because to know if data is available, it need to read, and you'll have the same problem.

There you have some tips where I spent a lot of hours trying to fix it :) I hope it will help you.

PD: Sorry for my English, I'm Spanish ^^'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM