JKD1.5的多线程启动socket实例

import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class MainServer {
private final ServerSocket serverSocket;
private final ExecutorService pool;
    public MainServer(int port, int clientCount) throws IOException {
      serverSocket = new ServerSocket(port);
      pool = Executors.newFixedThreadPool(clientCount);
    }

    public void serve() {
      try {
        while (true) {
          pool.execute(new Handler(serverSocket.accept()));
        }
      } catch (IOException ex) {
        pool.shutdown();
      }
    }

  class Handler implements Runnable {
    private final Socket socket;
    Handler(Socket socket) {
      this.socket = socket;
    }
    public void run() {
      // read and service request
      BufferedReader in=null;
      PrintWriter out=null;
      try
      {
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        out=new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())),true);
        while(true)
        {
          String str=in.readLine();
          if(!str.equals(null))
          System.out.println(str);
        Thread.currentThread().sleep(2000);
        }
      }catch(Exception e)
      {
        System.out.println(e.toString());
      }
    }
  }

  public static void main(String aa[])
  {
      try
      {
          new MainServer(444, 65535).serve();
      }catch(Exception e)
      {
          System.out.println(e.toString());
      }
      }
  }

 

Client端:

package test.bwl;  
  
import java.io.DataInputStream;  
import java.io.DataOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.net.Socket;  
import java.net.UnknownHostException;  
  
public class SocketClient {  
  
    public static void main(String[] args) {  
        Socket socket = null;  
        try {  
            socket = new Socket("127.0.0.1", 9991);  
            //向服务器端第一次发送字符串     
            OutputStream netOut = socket.getOutputStream();  
            DataOutputStream doc = new DataOutputStream(netOut);  
            DataInputStream in = new DataInputStream(socket.getInputStream());  
            //向服务器端第二次发送字符串     
            doc.writeUTF("list");  
            String res = in.readUTF();  
            System.out.println(res);  
            doc.writeUTF("bye");  
            res = in.readUTF();  
            System.out.println(res);  
            doc.close();  
            in.close();  
        } catch (UnknownHostException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        } finally {  
            if (socket != null) {  
                try {  
                    socket.close();  
                } catch (IOException e) {  
                }  
            }  
        }  
    }  
}  

 

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