자바로 간단한 TCP 서버 감청

17498 단어
--------------------------------------------- -----------------------------------------------

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 }

서비스 측은 클라이언트의 유동식 입력을 통해 감청과 정지를 실현한다.

좋은 웹페이지 즐겨찾기