### 實例1:
服務器回顯

~~~
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
/**
* 服務器回顯:服務端
* @author Administrator
*
*/
public class EchoServer {
public static void main(String[] args) {
Socket socket = null;
Scanner console = null;
InputStream is = null;
OutputStream os = null;
Scanner in = null;
PrintWriter out = null;
try {
// 1.開辟一個端口
ServerSocket ss = new ServerSocket(9527);
// 2.監聽連接請求,只監聽一次--阻塞操作
socket = ss.accept();
System.out.println("客戶端連接成功....");
console = new Scanner(System.in);
// 從socket管道獲取輸入輸出流
is = socket.getInputStream();
os = socket.getOutputStream();
// 包裝高級流
in = new Scanner(is);
out = new PrintWriter(os,true);
// 傳輸數據
String msg = "";
while(true) {
// 從控制臺獲取數據
msg = console.nextLine();
// 利用輸出流寫出去
out.println(msg);
// 利用輸入流讀取回顯信息
msg = in.nextLine();
System.out.println("EchoInfo:"+msg);
if(msg.equalsIgnoreCase("EXIT")){
break;
}
}
System.out.println("客戶端斷開連接...");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
console.close();
in.close();
out.close();
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
~~~
~~~
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
/**
* 服務器回顯:客戶端
* @author Administrator
*
*/
public class EchoClient {
public static void main(String[] args) {
Socket socket = null;
InputStream is = null;
OutputStream os = null;
Scanner in = null;
PrintWriter out = null;
try {
// 1.發起連接請求
socket = new Socket("10.25.41.46", 9527);
System.out.println("連接服務器成功...");
// 從socket管道獲取輸入輸出流
is = socket.getInputStream();
os = socket.getOutputStream();
// 包裝高級流
in = new Scanner(is);
out = new PrintWriter(os,true);
String msg = "";
while(true) {
// 利用輸入流讀取回顯信息
msg = in.nextLine();
// 利用輸出流寫出去
out.println(msg);
if(msg.equalsIgnoreCase("EXIT")){
break;
}
}
System.out.println("與服務器斷開連接...");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
in.close();
out.close();
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
~~~
***
### 實例2:
二進制文件的傳輸
