日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

记录TCP协议使用Socket连接,客户端请求服务器read()阻塞问题

發布時間:2025/3/17 编程问答 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 记录TCP协议使用Socket连接,客户端请求服务器read()阻塞问题 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

如圖:客戶端與服務端連接不上,服務端處于阻塞狀態:

首先,使用FileInputStream流輸入文件,使用FileInputStream.read()方法讀取文件返回int型(與題無關,加深記憶,總是忘記強轉成int);
其次,關于read()方法的介紹:Reads up to b.length bytes of data from this input stream into an array of bytes. This method blocks until some input is available; 表明read()方式是一個阻塞式方法;
解決方法:使用socket.shutdownOutput();關閉數據的輸出;

如圖:

客戶端:

@Testpublic void client(){InetAddress inet = null;Socket socket = null;OutputStream os = null;FileInputStream fis = null;//讀入文件try {//1.創建Socket // socket = new Socket(InetAddress.getByName(("127.0.0.1"),9988));inet = InetAddress.getByName("127.0.0.1");socket = new Socket(inet, 9988);//2.輸出流os = socket.getOutputStream();//3.輸入流fis = new FileInputStream(new File("程瀟.jpg"));//4.讀寫過程byte[] buffer = new byte[1024];int len;while((len = fis.read(buffer)) != -1){os.write(buffer,0,len);}//關閉數據的輸出socket.shutdownOutput();} catch (IOException e) {e.printStackTrace();} finally {//5.資源關閉if(os != null){try {os.close();} catch (IOException e) {e.printStackTrace();}}if(fis != null){try {fis.close();} catch (IOException e) {e.printStackTrace();}}if(socket != null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}}}

服務端:

@Testpublic void server(){Socket socket = null;InputStream is = null;FileOutputStream fos = null;try {ServerSocket ss = new ServerSocket(9988);socket = ss.accept();is = socket.getInputStream();fos = new FileOutputStream("瀟瀟子.jpg");byte[] buffer = new byte[1024];int len;while((len = is.read(buffer)) != -1){fos.write(buffer,0,len);}System.out.println("瀟瀟子服務端已收到來自:"+socket.getInetAddress().getHostName()+"的消息");} catch (IOException e) {e.printStackTrace();} finally {if(fos != null){try {fos.close();} catch (IOException e) {e.printStackTrace();}}if(is != null){try {is.close();} catch (IOException e) {e.printStackTrace();}}if(socket != null){try {socket.close();} catch (IOException e) {e.printStackTrace();}}}}

總結

以上是生活随笔為你收集整理的记录TCP协议使用Socket连接,客户端请求服务器read()阻塞问题的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。