Java的多线程Socket通信

转:http://wangtong40.iteye.com/blog/50633

package  com.wangtong.network;   
  
import  java.io.BufferedReader;   
import  java.io.IOException;   
import  java.io.InputStream;   
import  java.io.InputStreamReader;   
import  java.io.OutputStream;   
import  java.io.PrintWriter;   
import  java.net.ServerSocket;   
import  java.net.Socket;   
import  java.util.Scanner;   
  
public   class  MultipleServerSocket {   
  
     public   static   void  main(String[] args) {   
         try  {   
             int  i =  1 ;   
            ServerSocket serverSocket =  new  ServerSocket( 8189 );   
             while  ( true ) {   
                Socket incoming = serverSocket.accept();   
                System.out.println( "Thread...."  + i);  // count spawn   
                Runnable r =  new  ThreadedEchoHandler(incoming, i);   
                Thread t =  new  Thread(r);   
                t.start();   
                i++;   
  
            }   
        }  catch  (IOException e) {   
            e.printStackTrace();   
        }   
    }   
}   
  
class  ThreadedEchoHandler  implements  Runnable {   
  
     private  Socket socket;   
  
     private   int  counter;   
  
     public  ThreadedEchoHandler(Socket i,  int  c) {   
        socket = i;   
        counter = c;   
    }   
  
     public   void  run() {   
         try  {   
             try  {   
                BufferedReader in =  new  BufferedReader( new  InputStreamReader(   
                        socket.getInputStream()));   
                PrintWriter out =  new  PrintWriter(socket.getOutputStream());   
                 while  ( true ) {   
                    String str = in.readLine();   
                    System.out.println( "server:"  + str);   
                    out.println( "client receive"  + str);   
                    out.flush();   
                     if  (str.equals( "exit" ))   
                         break ;   
                }   
            }  finally  {   
                socket.close();   
            }   
        }  catch  (IOException e) {   
            e.printStackTrace();   
        }   
    }   
  
}   
 

你可能感兴趣的:(java,多线程,thread,.net,socket)