⒈ 所謂socket通常也稱作"套接字",用于描述IP地址和端口,是一個(gè)通信鏈的句柄。應(yīng)用程序通常通過"套接字"向網(wǎng)絡(luò)發(fā)出請求或者應(yīng)答網(wǎng)絡(luò)請求。
操作java socket時(shí)用到的最多的三個(gè)方法為:
accept():主要用于服務(wù)器端產(chǎn)生“阻塞”,等待客戶端的鏈接請求,并且返回一個(gè)客戶端的Socket實(shí)例;
getInputStream():方法主要用來獲得網(wǎng)絡(luò)連接輸入,同時(shí)返回一個(gè)InputStream對象實(shí)例;
getOutputStream():方法和上面的getInputStream相反。
⒉ 一般要建立Java的Socket連接,應(yīng)首先明確服務(wù)器端和客戶端,服務(wù)器端使用ServerSocket監(jiān)聽指定的端口,使用accept等待客戶端請求,鏈接鏈接,開始會話、完成會話后,關(guān)閉鏈接。(注意,一般socket的關(guān)閉都應(yīng)該是服務(wù)器端來進(jìn)行的,后面說);客戶端使用Socket對網(wǎng)絡(luò)中的某個(gè)服務(wù)器的某個(gè)端口發(fā)出鏈接請求,連接成功,開始會話,會話完成,Socket關(guān)閉。
示例代碼:
服務(wù)器端:
package?com.icer.server;import?java.io.BufferedReader;import?java.io.IOException;import?java.io.InputStreamReader;import?java.io.OutputStream;import?java.io.PrintWriter;import?java.net.ServerSocket;import?java.net.Socket;public?class?Server?{????private?ServerSocket?ss;????private?Socket?s;????private?BufferedReader?br;????private?PrintWriter?pw;????public?Server()?{????????try?{????????????????ss?=?new?ServerSocket(10000);????????????????System.out.println("Server?is?starting...");????????????????s?=?ss.accept();????????????????br?=?new?BufferedReader(new?InputStreamReader(s.getInputStream()));????????????????pw?=?new?PrintWriter(s.getOutputStream(),true);????????????????String?line?=?br.readLine();????????????????System.out.println(line);????????????????pw.println("your?word?is:"?+?line);????????????????//pw.println("helloworld");????????????????br.close();????????????????pw.close();????????}?catch?(IOException?ie)?{????????????ie.printStackTrace();????????}????}????public?static?void?main(String[]?args)?throws?Exception?{????????new?Server();????}}
客戶端:
package?com.icer.client;import?java.io.BufferedReader;import?java.io.File;import?java.io.FileInputStream;import?java.io.IOException;import?java.io.InputStreamReader;import?java.io.PrintWriter;import?java.net.Socket;public?class?Client?{????private?Socket?s;????private?BufferedReader?br;????//private?BufferedReader?line;????private?PrintWriter?pw;????private?String?line?=?"";????public?Client()?{????????try{????????????s?=?new?Socket("127.0.0.1",10000);????????????pw?=?new?PrintWriter(s.getOutputStream(),true);????????????br?=?new?BufferedReader(new?InputStreamReader(s.getInputStream()));????????????pw.println("hello");????????????line?=?br.readLine();????????????System.out.println(line);????????????br.close();????????????pw.close();????????}catch(IOException?ie){????????????ie.printStackTrace();????????}????}????public?static?void?main(String[]?args)?throws?Exception?{????????new?Client();????}}
以上就是天津卓眾教育java培訓(xùn)機(jī)構(gòu)的小編針對“Java socket編程實(shí)例代碼講解”的內(nèi)容進(jìn)行的回答,希望對大家有所幫助,如有疑問,請?jiān)诰€咨詢,有專業(yè)老師隨時(shí)為你服務(wù)。