上图描述了客户端可服务端的网络连接以及数据交换。下面的代码是基于IO的方式去通信的。
Server代码:
public class ServerEcho {
static int port=8080;
static ServerSocket serverSocket=null;
public ServerEcho() throws IOException {
serverSocket=new ServerSocket(port);
System.out.println("服务器已经启动");
}
private String echo(String msg){
return "echo:"+msg;
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream outputStream = socket.getOutputStream();
return new PrintWriter(outputStream,true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream inputStream = socket.getInputStream();
return new BufferedReader(new InputStreamReader(inputStream));
}
public void service(){
while (true){
Socket socket=null;
try {
socket = serverSocket.accept();
System.out.println("新建连接:"+socket.getInetAddress()+":"+socket.getPort());
//服务端读取数据和打印数据
BufferedReader reader = getReader(socket);
PrintWriter writer = getWriter(socket);
String msg=null;
while((msg=reader.readLine())!=null){
System.out.println(msg);
writer.println(echo(msg));
if("bye".equals(msg)){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if(socket!=null){
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
public static void main(String[] args) throws IOException {
new ServerEcho().service();
}
}
客户端d代码如下:
public class ClientEcho {
static int port = 8080;
static Socket socket = null;
static String host = "127.0.0.1";
public ClientEcho() throws IOException {
socket = new Socket(host, port);
}
private PrintWriter getWriter(Socket socket) throws IOException {
OutputStream outputStream = socket.getOutputStream();
return new PrintWriter(outputStream, true);
}
private BufferedReader getReader(Socket socket) throws IOException {
InputStream inputStream = socket.getInputStream();
return new BufferedReader(new InputStreamReader(inputStream));
}
public void talk() {
try {
BufferedReader reader = getReader(socket);
PrintWriter writer = getWriter(socket);
//本地输入数据
BufferedReader localReader=new BufferedReader(new InputStreamReader(System.in));
String msg=null;
while((msg=localReader.readLine())!=null){
writer.println(msg);
System.out.println(reader.readLine());
if("bye".equals(msg)){
break;
}
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
new ClientEcho().talk();
}
}