java的socket读取一行就结束运行了?使用这种方法可以读取多行数据!
生活随笔
收集整理的這篇文章主要介紹了
java的socket读取一行就结束运行了?使用这种方法可以读取多行数据!
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
目錄
引出問題
第一種(只能讀取一行數據)
第二種(可以讀取多行數據)
引出問題
寫一個socket的公共方法,結果發現socket讀取一行數據就結束了,百思不得其解。
在網上也找了一些資料,很多也有坑,這里貼出來自己用的兩種方法,以后就不用一直找解決方案了。
第一種(只能讀取一行數據)
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.PrintWriter; import java.net.Socket;public class Client {final static String ADDRESS = "127.0.0.1";final static int PORT = 8765;public static void main(String[] args) {Socket socket = null;BufferedReader in = null;PrintWriter out = null;try {socket = new Socket(ADDRESS, PORT);in = new BufferedReader(new InputStreamReader(socket.getInputStream()));out = new PrintWriter(socket.getOutputStream(), true);//向服務器端發送數據out.println("接收到客戶端的請求數據...");String response = in.readLine();System.out.println("Client: " + response);} catch (Exception e) {e.printStackTrace();} finally {if(in != null){try {in.close();} catch (IOException e) {e.printStackTrace();}}if(out != null){try {out.close();} catch (Exception e) {e.printStackTrace();}}if(socket != null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}socket = null;}} }第二種(可以讀取多行數據)
import java.io.*; import java.net.Socket;public class PostmanSocketController {public String socketClient(String ip, Integer port, String reqInfo, String bm) throws Exception {Socket s = null;OutputStream out = null;InputStream in = null;String rs = "";try {s = new Socket(ip, port);s.setSendBufferSize(4096);s.setTcpNoDelay(true);s.setSoTimeout(60*1000);s.setKeepAlive(true);out = s.getOutputStream();//in = s.getInputStream();//準備報文msg//編碼out.write(reqInfo.getBytes(bm));out.flush();rs = readAll(s, bm);} catch (Exception e) {throw e;}finally{try {if(out!=null){out.close();out = null;}if(in!=null){in.close();in = null;}if(s!=null){s.close();s = null;}} catch (IOException e) {e.printStackTrace();}}return rs;}public static String readAll(Socket socket, String bm) throws IOException {BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream(), bm));StringBuilder sb = new StringBuilder();String line;while ((line = reader.readLine()) != null)sb.append(line).append("\n");return sb.toString();}}?
總結
以上是生活随笔為你收集整理的java的socket读取一行就结束运行了?使用这种方法可以读取多行数据!的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 什么是分布式锁?redis、zookee
- 下一篇: 巨详细的prometheus+grafa