網絡應用分為客戶端和服務端兩部分,而Socket類是負責處理客戶端通信的Java類。通過這個類可以連接到指定IP或域名的服務器上,并且可以和服務器互相發送和接受數據。
對于Socket通信簡述,服務端往Socket的輸出流里面寫東西,客戶端就可以通過Socket的輸入流讀取對應的內容。Socket與Socket之間是雙向連通的,所以客戶端也可以往對應的Socket輸出流里面寫東西,然后服務端對應的Socket的輸入流就可以讀出對應的內容。
例1:客戶端的簡略寫法(一)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
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:客戶端簡略寫法(二)。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
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:客戶端的完整寫法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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通信(一)之客戶端程序 發送和接收數據的相關知識,小編就給大家介紹到這里,更多信息請登陸服務器之家網站了解更多內容!