【问题标题】:send and receive string and file over socket with streams通过带有流的套接字发送和接收字符串和文件
【发布时间】:2018-01-23 11:37:09
【问题描述】:

我有一个应用程序通过套接字在本地网络上与其他设备进行通信。在那我还想传输文件和文本。 我的问题是我不知道如何获取文件和文本并在接收中管理它们!

这是我的文本接收器:

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

    }

如何同时接收文本和文件?

【问题讨论】:

    标签: android sockets stream


    【解决方案1】:

    这就是为什么会有如此多的应用程序级网络协议,例如 HTTP、FTP、SMTP。

    在您的情况下,您需要两种类型的消息,一种是字符串,另一种是文件。每条消息都应符合预定义的格式。例如,

    [4字节消息类型] + [4字节消息长度] + [消息内容]

    您在发送方构造消息,并在接收方解析消息。

    但是,在大多数情况下,您不必重新发明*。在互联网上搜索是否有适合您的现有协议。

    【讨论】:

    最近更新 更多