我有一个应用程序可以通过套接字在本地网络上与其他设备进行通信。因为我还想传输文件和文本。 我的问题是我不知道如何获取文件和文本并在接收时管理它们!
这是我的文本接收器:
try {
outputStream = new DataOutputStream(socket.getOutputStream());
outputstream_external = outputStream;
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
log("success to set streams");
}
catch (IOException e1) {
log("Error: Connection is not stable, exit");
shutdown();
}
while (true) {
String message = null;
try {
message = inputStream.readLine();
if (message == null) {
return;
}
G.log(message);
JSONObject object = new JSONObject(message);
String command = object.getString(Command.COMMAND);
G.log(message);
这是我的短信发送者:
public void sendCommand(String command) {
G.log("send command + " + command);
command = command.replace("\n", " ") + "\n";
if (outputStream == null) {
return;
}
final String commend = command;
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
try {
outputStream.write(commend.getBytes());
}
catch (IOException e) {
e.printStackTrace();
G.log("sendCommand into catch");
}
}
});
thread.start();
}
我怎样才能同时接收文本和文件?
最佳答案
这就是为什么有这么多应用层网络协议(protocol),如 HTTP、FTP、SMTP。
在您的情况下,您需要两种类型的消息,一种是字符串,另一种是文件。每条消息都应符合预定义的格式。例如,
[4字节消息类型] + [4字节消息长度] + [消息内容]
您在发送方构造消息,并在接收方解析消息。
但是,在大多数情况下,您不必重新发明轮子。在 Internet 上搜索以查找是否有适合您的现有协议(protocol)。
关于android - 使用流通过套接字发送和接收字符串和文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45694710/