我有一个名为Message的Serializable
对象,我希望它包含音乐,我有它的路径。
我不想使用inputStream/outputStream
直接发送音乐,我想把它放在我发送的消息中。
怎么可能这样做?
客户代码:
if (intent.getAction().equals(ACTION_SEND_MESSAGE)){
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
Message lcm = (Message) intent.getSerializableExtra(DATA);
Air.get().log("MessageService", "Send message: "+lcm.getClass().getSimpleName());
ObjectInputStream inputStream;
try {
Log.d(WiFiDirectActivity.TAG, "Opening client socket - "+host+":"+port);
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
OutputStream os = socket.getOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(os);
oos.writeObject(lcm);
oos.close();
os.close();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
} catch(Exception e){
}
finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
和服务器部分:
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
while (true) {
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
InputStream is = client.getInputStream();
ObjectInputStream ois = new ObjectInputStream(is);
Message to = (Message) ois.readObject();
if (to != null) {
Log.d(to.toString(), to.toString());
}
}