记录TCP协议使用Socket连接,客户端请求服务器read()阻塞问题
生活随笔
收集整理的這篇文章主要介紹了
记录TCP协议使用Socket连接,客户端请求服务器read()阻塞问题
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
如圖:客戶端與服務(wù)端連接不上,服務(wù)端處于阻塞狀態(tài):
首先,使用FileInputStream流輸入文件,使用FileInputStream.read()方法讀取文件返回int型(與題無關(guān),加深記憶,總是忘記強轉(zhuǎn)成int);
其次,關(guān)于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();關(guān)閉數(shù)據(jù)的輸出;
如圖:
客戶端:
@Testpublic void client(){InetAddress inet = null;Socket socket = null;OutputStream os = null;FileInputStream fis = null;//讀入文件try {//1.創(chuàng)建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);}//關(guān)閉數(shù)據(jù)的輸出socket.shutdownOutput();} catch (IOException e) {e.printStackTrace();} finally {//5.資源關(guān)閉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();}}}}服務(wù)端:
@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("瀟瀟子服務(wù)端已收到來自:"+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();}}}}總結(jié)
以上是生活随笔為你收集整理的记录TCP协议使用Socket连接,客户端请求服务器read()阻塞问题的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 大型网站技术架构文摘
- 下一篇: 读取网络数据缓存在本地 流程图