Question

I am trying get a running example for WiFi Peer-to-Peer, where one user can send a simple string to the other user. In the example in the documentation, only files are sent - how can I just send a string without files and stuff?

Code from documentation:

Sending:

 OutputStream outputStream = socket.getOutputStream();
    ContentResolver cr = context.getContentResolver();
    InputStream inputStream = null;
    inputStream = cr.openInputStream(Uri.parse("path/to/picture.jpg"));
    while ((len = inputStream.read(buf)) != -1) {
        outputStream.write(buf, 0, len);
    }
    outputStream.close();
    inputStream.close();

Receiving:

final File f = new File(Environment.getExternalStorageDirectory() + "/"
                + context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
                + ".jpg");

        File dirs = new File(f.getParent());
        if (!dirs.exists())
            dirs.mkdirs();
        f.createNewFile();
        InputStream inputstream = client.getInputStream();
        copyFile(inputstream, new FileOutputStream(f));
        serverSocket.close();
        return f.getAbsolutePath();

How would I need to modify this code to Send/Receive Strings? (without files).

Was it helpful?

Solution

  1. Convert your String to a byte array using String.getBytes()
  2. Write that array into your OutputStream

OTHER TIPS

String mData = "YOUR DATA";
int mArraySize = 1024; 
try{
byte[] data = new byte[mArraySize];
data = mData.getBytes();
outputStream = mSocket.getOutputStream();
int count = data.length;
outputStream.write(data, 0, count);
}catch(Exception e){
    e.printStackTrace();
}   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top