### 实例1:
服务器回显
![](https://box.kancloud.cn/6a60c94dc58b5eecf67642df82e293cb_717x610.png)
~~~
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:
二进制文件的传输
![](https://box.kancloud.cn/02dcb85de64362e1cc93d981f4e818e3_717x606.png)