Reputation: 1134
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).
Upvotes: 0
Views: 2629
Reputation: 1345
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();
}
Upvotes: 0
Reputation: 12919
String
to a byte array using String.getBytes()
OutputStream
Upvotes: 1