2014-02-19 81 views
0

我想獲得一個WiFi對等的運行示例,其中一個用戶可以發送一個簡單的字符串到另一個用戶。在example in the documentation,只有文件被髮送 - 我怎麼才能發送沒有文件和東西的字符串?從文檔發送簡單的字符串,而不是文件通過WiFi P2P

代碼:

發送:

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

我怎麼會需要修改這個代碼來發送/接收字符串? (沒有文件)。

回答

1
  1. 將您String使用String.getBytes()
  2. 該數組寫入的字節數組到您OutputStream
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(); 
} 
相關問題