服务器响应多个Client的Socket请求

来源:互联网 发布:com域名续费价格 编辑:程序博客网 时间:2024/05/19 02:21
  • package test;   
  •   
  • import java.io.*;   
  • import java.net.*;   
  •   
  • public class MultiServer {   
  •     public MultiServer() throws IOException {   
  •         ServerSocket ss=new ServerSocket(7777);   
  •         while(true){   
  •             Socket socket=ss.accept();   
  •             new DealMessage(socket).start();   
  •         }   
  •     }   
  •     public static void main(String[] args) {   
  •         try {   
  •             new MultiServer();   
  •         } catch (IOException e) {   
  •             e.printStackTrace();   
  •         }   
  •     }   
  • }   
  •   
  • class DealMessage extends Thread {   
  •     private Socket socket;   
  •     private InputStream in;   
  •     private OutputStream out;   
  •   
  •     public DealMessage(Socket s) throws IOException {   
  •         this.socket = s;   
  •         this.in = socket.getInputStream();   
  •         this.out = socket.getOutputStream();   
  •     }   
  •   
  •     public void run() {   
  •         try {   
  •             BufferedReader br = new BufferedReader(new InputStreamReader(in));   
  •             System.out.println("you IP is: " + socket.getInetAddress()+":"+socket.getPort());   
  •             System.out.println("you enter is: " + br.readLine());   
  •         } catch (IOException e) {   
  •             e.printStackTrace();   
  •         }   
  •     }   
  •   
  •     public void finalize() throws IOException {   
  •         if (in != null) {   
  •             in.close();   
  •         }   
  •         if (out != null) {   
  •             out.close();   
  •         }   
  •     }   
  • }  
  • 原创粉丝点击