问题描述
- socket通信为什么获取不到流里面的数据
-
就是我在用while循环读取数据的时候读不出来?但是我打印new String(buf).trim()就有数据?
我们后台是.net写的。请问这是个什么问题
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(); StringBuffer sb = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(socket.getInputStream())); System.out.println("reader:"+reader); int len = 0; char[] buf = new char[1024]; while ((len = reader.read(buf)) != -1) { sb.append(buf, 0, len); System.out.println(new String(buf).trim()); } result = sb.toString(); 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(); } } public static String streamToString(InputStream is) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { baos.write(buffer, 0, len); } baos.close(); is.close(); byte[] byteArray = baos.toByteArray(); return new String(byteArray); } catch (Exception e) { return null; } }
}
解决方案
问题问的不清楚,“while循环读取数据的时候读不出来”是什么意思?在哪一行?
时间: 2024-09-20 05:48:32