網(wǎng)絡(luò)應(yīng)用分為客戶端和服務(wù)端兩部分,而Socket類是負(fù)責(zé)處理客戶端通信的Java類。通過這個(gè)類可以連接到指定IP或域名的服務(wù)器上,并且可以和服務(wù)器互相發(fā)送和接受數(shù)據(jù)。
對于Socket通信簡述,服務(wù)端往Socket的輸出流里面寫東西,客戶端就可以通過Socket的輸入流讀取對應(yīng)的內(nèi)容。Socket與Socket之間是雙向連通的,所以客戶端也可以往對應(yīng)的Socket輸出流里面寫東西,然后服務(wù)端對應(yīng)的Socket的輸入流就可以讀出對應(yīng)的內(nèi)容。
例1:客戶端的簡略寫法(一)。
Socket client = null;try{client = new Socket(Ip,Port);String msg="發(fā)送的數(shù)據(jù)內(nèi)容!";//得到socket讀寫流,向服務(wù)端程序發(fā)送數(shù)據(jù) client.getOutputStream().write(msg.getBytes());byte[] datas = new byte[2048];//從服務(wù)端程序接收數(shù)據(jù)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="訪問的服務(wù)器返回內(nèi)容!";//得到socket讀寫流,向服務(wù)端程序發(fā)送數(shù)據(jù) client.getOutputStream().write(msg.getBytes());byte[] datas = new byte[2048];//從服務(wù)端程序接收數(shù)據(jù)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連接,指定服務(wù)器位置及端口 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進(jìn)行讀寫操作 String sendInfo="向服務(wù)器發(fā)送的數(shù)據(jù)信息!";pw.write(sendInfo); pw.flush(); socket.shutdownOutput(); //接收服務(wù)器的相應(yīng) String replyInfo=null; while(!((replyInfo=br.readLine())==null)){ System.out.println("接收服務(wù)器的數(shù)據(jù)信息:"+replyInfo); } //4.關(guān)閉資源 br.close(); is.close(); pw.close(); os.close(); socket.close(); } catch (UnknownHostException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }關(guān)于Java Socket通信(一)之客戶端程序 發(fā)送和接收數(shù)據(jù)的相關(guān)知識,小編就給大家介紹到這里,更多信息請登陸武林網(wǎng)網(wǎng)站了解更多內(nèi)容!
新聞熱點(diǎn)
疑難解答
圖片精選