2 qq 34077991 qq_34077991 于 2016.03.30 10:14 提问

Android socket通信接受不完服务端返回的数据

package com.jm.jmsdk_tools_jar;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;

public class Socketest {

public synchronized static String sendMsg(String host, int port, String msg) {
    // 写
    String result = null;
    InputStream is = null;
    OutputStreamWriter osw = null;
    BufferedReader reader = null;
    Socket socket = new Socket();

    try {
        if (port < 0) {
            return "";
        }
        InetSocketAddress isa = new InetSocketAddress(host, port);
        socket.connect(isa, 10000);
        osw = new OutputStreamWriter(socket.getOutputStream());
        BufferedWriter writer = new BufferedWriter(osw);
        writer.write(msg);
        writer.flush();
        byte[] a = readStream(socket.getInputStream());
        result = new String(a);

        System.out.println("result:" + result);
    } catch (SocketTimeoutException e) {
        e.printStackTrace();
        return null;
    } catch (ConnectException e) {
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    } finally {
        try {
            if (reader != null)
                try {
                    reader.close();
                } catch (Exception e) {
                }
            closeOutputStreamWriter(osw);
            closeInputStream(is);
            closeSocket(socket);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return result;
}

private static void closeOutputStreamWriter(OutputStreamWriter osw) throws IOException {
    if (osw != null) {
        osw.close();
    }
}

private static void closeInputStream(InputStream is) throws IOException {
    if (is != null) {
        is.close();
    }
}

private static void closeSocket(Socket socket) throws IOException {
    if (socket != null) {
        socket.close();
    }
}

private static byte[] readStream(InputStream inputStream) throws IOException {
    int count = 0;
    while (count == 0) {
        count = inputStream.available();
    }
    byte[] b = new byte[count];
    inputStream.read(b);

    return b;
}

}

1个回答

wstcok2003
wstcok2003   2016.03.30 11:06

服务器防火墙关了吗?
安卓机网络权限开了吗?

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!