網路應用分為用戶端和服務端兩部分,而Socket類是負責處理用戶端通訊的Java類。通過這個類可以串連到指定IP或網域名稱的伺服器上,並且可以和伺服器互相發送和接受資料。
對於Socket通訊簡述,服務端往Socket的輸出資料流裡面寫東西,用戶端就可以通過Socket的輸入資料流讀取對應的內容。Socket與Socket之間是雙向連通的,所以用戶端也可以往對應的Socket輸出資料流裡面寫東西,然後服務端對應的Socket的輸入資料流就可以讀出對應的內容。
例1:用戶端的簡略寫法(一)。
Socket client = null;try{client = new Socket(Ip,Port);String msg="發送的資料內容!";//得到socket讀寫流,向服務端程式發送資料 client.getOutputStream().write(msg.getBytes());byte[] datas = new byte[2048];//從服務端程式接收資料client.getInputStream().read(datas);System.out.println(new String(datas));}catch(Exception e){e.printStackTrace();}finally {if (client != null) {try {client.close();} catch (IOException e) {System.out.println("systemerr:" +e);}}}
例2:用戶端簡略寫法(二)。
try{client = new Socket();SocketAddress socketAddress = new InetSocketAddress(Ip,Port);client.connect(socketAddress, 3000);String msg="訪問的伺服器返回內容!";//得到socket讀寫流,向服務端程式發送資料 client.getOutputStream().write(msg.getBytes());byte[] datas = new byte[2048];//從服務端程式接收資料client.getInputStream().read(datas);System.out.println(new String(datas));}catch(Exception e){e.printStackTrace();}finally {if (client != null) {try {client.close();} catch (IOException e) {System.out.println("systemerr:" +e);}}}
例3:用戶端的完整寫法。
try { //1.建立用戶端socket串連,指定伺服器位置及連接埠 Socket socket =new Socket(Ip,Port); //2.得到socket讀寫流 OutputStream os=socket.getOutputStream(); PrintWriter pw=new PrintWriter(os); //輸入資料流 InputStream is=socket.getInputStream(); BufferedReader br=new BufferedReader(new InputStreamReader(is)); //3.利用流按照一定的操作,對socket進行讀寫操作 String sendInfo="向伺服器發送的資料資訊!";pw.write(sendInfo); pw.flush(); socket.shutdownOutput(); //接收伺服器的相應 String replyInfo=null; while(!((replyInfo=br.readLine())==null)){ System.out.println("接收伺服器的資料資訊:"+replyInfo); } //4.關閉資源 br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }
關於Java Socket通訊(一)之用戶端程式 發送和接收資料的相關知識,小編就給大家介紹到這裡,更多資訊請登陸雲棲社區網站瞭解更多內容!