通过WiFi P2P发送简单的字符串而不是文件

时间:2014-02-19 13:04:28

标签: android wifi p2p

我正在尝试获取WiFi Peer-to-Peer的运行示例,其中一个用户可以向另一个用户发送简单的字符串。在example in the documentation中,只发送文件 - 如何发送没有文件和内容的字符串?

文档中的代码:

发送:

 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();

接收:

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();

我如何修改此代码以发送/接收字符串? (没有文件)。

2 个答案:

答案 0 :(得分:1)

  1. 使用String
  2. String.getBytes()转换为字节数组
  3. 将该数组写入OutputStream

答案 1 :(得分:0)

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();
}