Socket通信簡(jiǎn)介
Java Socket可實(shí)現(xiàn)客戶端-服務(wù)端的雙向?qū)崟r(shí)通信。在java.net包中定義了兩個(gè)類(lèi)socket和serversocket分別實(shí)現(xiàn)雙向連接的client和server端。
Socket通信實(shí)現(xiàn)方式
服務(wù)器端(非多線程)
實(shí)現(xiàn)流程:
- 用指定的端口實(shí)例化一個(gè)ServerSocket對(duì)象,服務(wù)器可以通過(guò)這個(gè)端口監(jiān)聽(tīng)從客戶端發(fā)來(lái)的連接請(qǐng)求掏颊;
- 調(diào)用ServerSocket的
accept()
方法,監(jiān)聽(tīng)連接從端口來(lái)的請(qǐng)求迄损,此方法是阻塞的省有; - 利用accept方法返回的客戶端socket對(duì)象進(jìn)行讀寫(xiě)IO操作;
- 關(guān)閉Socket對(duì)象贯涎。
代碼:
public class ServerS {
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(11111);
Socket client = server.accept();
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
String str = in.readLine();
System.out.println(str);
out.println("has receive....");
out.flush();
if (str.equals("end"))
break;
}
client.close();
}
}
客戶端
實(shí)現(xiàn)流程:
- 用服務(wù)器端提供的IP地址和端口進(jìn)行實(shí)例化听哭;
- 調(diào)用
connect()
方法,連接服務(wù)器塘雳; - 獲取Socket上面的流陆盘,封裝到進(jìn)BufferedReader/PrintWriter的實(shí)例,以進(jìn)行讀寫(xiě)败明;
- 利用Socket提供的getInputStream和getOutputStream方法隘马,和服務(wù)器進(jìn)行交互;
- 關(guān)閉Socket對(duì)象妻顶。
代碼:
public class Client {
public static void main(String[] args) throws Exception, Exception {
Socket server = new Socket(InetAddress.getLocalHost(), 11111);
BufferedReader in = new BufferedReader(new InputStreamReader(server.getInputStream()));
PrintWriter out = new PrintWriter(server.getOutputStream());
BufferedReader wt = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = wt.readLine();
out.println(str);
out.flush();
if (str.equals("end")) {
break;
}
System.out.println(in.readLine());
}
server.close();
}
}
服務(wù)器端(多線程)
實(shí)現(xiàn)流程:
- 服務(wù)器端創(chuàng)建ServerSocket酸员,循環(huán)調(diào)用
accept()
等待客戶端連接蜒车; - 客戶端創(chuàng)建Socket并請(qǐng)求和服務(wù)器端連接;
- 服務(wù)器端接受客戶端請(qǐng)求沸呐,創(chuàng)建ServerSocket與該客戶建立連接醇王;
- 建立連接的兩個(gè)Socket在一個(gè)單獨(dú)的線程上對(duì)話;
- 服務(wù)器端繼續(xù)等待新的連接崭添。
代碼:
public class MultiClient extends Thread {
private Socket client;
public MultiClient(Socket c) {
this.client = c;
}
public void run() {
try {
BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
PrintWriter out = new PrintWriter(client.getOutputStream());
while (true) {
String str = in.readLine();
System.out.println(str);
out.println("has receive....");
out.flush();
if (str.equals("end"))
break;
}
client.close();
} catch (IOException ex) {
} finally {
}
}
public static void main(String[] args) throws IOException {
ServerSocket server = new ServerSocket(11111);
while (true) {
MultiClient mc = new MultiClient(server.accept());
mc.start();
}
}
}
說(shuō)明:
java方面的socket編程基本完結(jié)寓娩,下一章將介紹Android中的LocalServerSocket編程。