---------------------------------------------服务端-----------------------------------------------

1
package C; 2 import java.io.*; 3 import java.net.*; 4 5 public class Server extends ServerSocket 6 { 7 public Server(int serverPort) throws IOException 8 { 9 super(serverPort); 10 try 11 { 12 while (true) 13 { 14 Socket socket = accept(); 15 new ServerThread(socket); 16 } 17 } catch (IOException e) { 18 e.printStackTrace(); 19 } 20 finally { 21 close(); 22 } 23 } 24 class ServerThread extends Thread /*建立服务端线程*/ 25 { 26 private Socket socket; 27 private BufferedReader in; 28 private PrintWriter out; 29 public ServerThread(Socket s) throws IOException 30 { 31 this.socket = s; 32 in = new BufferedReader(new InputStreamReader( 33 socket.getInputStream(), "GB2312")); /*国标码*/ 34 out = new PrintWriter(socket.getOutputStream(),true); 35 start(); /*开始线程*/ 36 } 37 38 public void run() 39 { 40 try { 41 while (true) 42 { 43 String line = in.readLine(); 44 if ("finish".equals(line)) 45 { 46 System.out.println("服务器已停止监听"); 47 break; 48 } 49 System.out.println("接收到的数据:" + line); 50 String msg = "'" + line + "'已传输到服务器端."; 51 out.println(msg); 52 out.flush(); 53 } 54 out.close(); 55 in.close(); 56 socket.close(); 57 } 58 catch (IOException e) 59 { 60 e.printStackTrace(); 61 } 62 } 63 } 64 public static void main(String[] args) throws IOException 65 { 66 System.out.println("服务器开始运行......"); 67 new Server(2333); /*绑定端口号*/ 68 } 69 70 }
---------------------------------------------客户端-----------------------------------------------

1
package C; 2 import java.io.*; 3 import java.net.*; 4 5 public class Client 6 { 7 private Socket socket; /*定义socket连接*/ 8 private BufferedReader reader; /*从字符输入流读取文本*/ 9 private PrintWriter writer; /*打印到文本输出流*/ 10 11 public Client(int serverPort) { /*定义客户端端口号*/ 12 try { /*抛异常*/ 13 socket = new Socket("123.206.78.55", serverPort); 14 reader = new BufferedReader( 15 new InputStreamReader(socket.getInputStream())); /*标准输入输出流*/ 16 writer = new PrintWriter(socket.getOutputStream()); 17 18 while (true) 19 { 20 21 BufferedReader in = new BufferedReader( 22 new InputStreamReader(System.in)); 23 String message = in.readLine(); 24 writer.println(message); 25 writer.flush(); /*不关闭流,清空输入缓存区*/ 26 27 if ("finish".equals(message)) 28 { 29 System.out.println("服务器已停止监听"); 30 break; 31 } 32 String received = reader.readLine(); 33 System.out.println(received); 34 } 35 36 writer.close(); 37 reader.close(); /*关闭流*/ 38 socket.close(); 39 40 } 41 catch (UnknownHostException ex) 42 { 43 ex.printStackTrace(); 44 } 45 catch (IOException ex) 46 { 47 ex.printStackTrace(); /*在命令行打印异常信息在程序中出错的位置及原因*/ 48 } 49 } 50 51 52 53 public static void main(String[] args) 54 { 55 new Client(2333); /*绑定端口号*/ 56 } 57 }

服务端是通过客户端的流式输入来实现监听和停止监听的。