//<--------------服務端代碼-------------------->
public class SocketReadLister implements Runnable {
private final int tcpPort=9999; private ServerSocket serverSocket; @Override public void run() { try { serverSocket = new ServerSocket(this.tcpPort); while(true){ Socket socket = serverSocket.accept(); //socket.setSoTimeout(5*1000);//設置讀取數據超時時間爲5s new Thread(new SocketReadThread(socket)).start(); } }catch (Exception e){ e.printStackTrace(); } } public static void main(String[] args) throws Exception{ new Thread(new SocketReadLister()).start(); } } public class SocketReadThread implements Runnable { private Socket socket; public SocketReadThread(Socket socket) { this.socket = socket; } @Override public void run() { byte[] data = new byte[1024]; try { InputStream is=socket.getInputStream(); int length=0; int num=is.available(); while((length = is.read(data)) != -1){ String result = new String(data); System.out.println("數據available:"+num); System.out.println("數據:"+result); System.out.println("length:" + length); } System.out.print("結束數據讀取:"+length); }catch (SocketTimeoutException socketTimeoutException){ try { Thread.sleep(2*1000); }catch (Exception e) { e.printStackTrace(); } run(); } catch (Exception e){ e.printStackTrace(); try { socket.close(); }catch (IOException io){ io.printStackTrace(); } } } }
//<---------------------客戶端代碼---------------------------->
public class SocketClient implements Runnable {
private final int tcpPort=9999; private Socket socket; @Override public void run() { String msg = "ab23567787hdhfhhfy"; byte[] byteMsg = msg.getBytes(); try { socket = new Socket("127.0.0.1", 9999); OutputStream out = socket.getOutputStream(); InputStream inputStream=socket.getInputStream(); out.write(byteMsg); Thread.sleep(10*1000); char[] chars=msg.toCharArray(); String str=""; /*out.flush();*/ for(int i=0;i<msg.length();i++) { str=chars[i]+"-"+i; out.write(str.getBytes()); Thread.sleep(1*1000); } byte[] bytes=new byte[8]; while(true) { if(inputStream.available()>0) { if(inputStream.read(bytes)!=-1) { System.out.println(new String(bytes)); } } Thread.sleep(10*1000); } } catch (Exception e) { e.printStackTrace(); try { socket.close(); } catch (IOException e2) { e2.printStackTrace(); } } } public static void main(String[] args) { new Thread(new SocketClient()).start(); } }
while(true){
if(is.available()>0){ is.read(data); } }
if (nRecv < nRecvNeed){
int nSize = 0; wsaBuf=new byte[nRecvNeed-nRecv]; int readCount = 0; // 已經成功讀取的字節的個數 try { while (readCount < wsaBuf.length) { //Thread.sleep(100);//讀取以前先將線程休眠,避免循環時,程序佔用CPU太高 try { availableNum=inputStream.available(); if(availableNum>0){ readCount += inputStream.read(wsaBuf, readCount, (wsaBuf.length - readCount));//避免數據讀取不完整 } }catch (SocketTimeoutException timeOut){ System.out.println("讀取超時,線程執行休眠操做,2秒後再讀取"); Thread.sleep(2*1000); } } }catch (Exception e){ System.out.println("讀取數據異常"); e.printStackTrace(); close();//關閉socket鏈接 break; } nSize=wsaBuf.length; nRecv+=nSize; }