//服务器端代码,服务器端代码,服务器端代码 package com.okme.MyServer; import java.io.*; import java.net.ServerSocket; import java.net.Socket; public class EchoServerDemo { public static void main(String[] args) { //创建一个服务端的Socket,1020-65535 try { ServerSocket server = new ServerSocket(2000); System.out.println("服务器已经启动,正在等待客户端连接"); //等待客户端的连接,造成阻塞,如果有客户端连接成功,立即返回一个Socket对象 Socket socket = server.accept(); System.out.println(socket.getInetAddress().getHostAddress()+"客户端连接成功"); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); //通过输入流读取网络数据,如果没有数据也造成阻塞 String info = br.readLine(); System.out.println(info); PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream())); ps.println("echo:"+info); //关闭 ps.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } }
//客户端代码,客户端代码,客户端代码
package com.okme.MyServer; import java.io.*; import java.net.Socket; public class EchoClientDemo { public static void main(String[] args) { //创建一个Socket对象,指定要连接的服务器 try { Socket socket = new Socket("localhost", 2000); //获取socket的输入输出流 PrintStream ps = new PrintStream(new BufferedOutputStream(socket.getOutputStream())); BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream())); ps.println("hello my name is xiaongda"); ps.flush(); //读取服务器端返回的数据 String info = br.readLine(); System.out.println(info); ps.close(); br.close(); } catch (IOException e) { e.printStackTrace(); } } }