码迷,mamicode.com
首页 > 编程语言 > 详细

多线程Java Socket编程示例(转)

时间:2014-11-16 23:02:08      阅读:262      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   color   ar   os   sp   java   

这篇做为学习孙卫琴<<Java网络编程精解>>的学习笔记吧.其中采用Java 5的ExecutorService来进行线程池的方式实现多线程,模拟客户端多用户向同一服务器端发送请求.

1.服务端

bubuko.com,布布扣package sterning;
bubuko.com,布布扣
bubuko.com,布布扣import java.io.BufferedReader;
bubuko.com,布布扣import java.io.IOException;
bubuko.com,布布扣import java.io.InputStream;
bubuko.com,布布扣import java.io.InputStreamReader;
bubuko.com,布布扣import java.io.OutputStream;
bubuko.com,布布扣import java.io.PrintWriter;
bubuko.com,布布扣import java.net.*;
bubuko.com,布布扣import java.util.concurrent.*;
bubuko.com,布布扣
bubuko.com,布布扣public class MultiThreadServer {
bubuko.com,布布扣    private int port=8821;
bubuko.com,布布扣    private ServerSocket serverSocket;
bubuko.com,布布扣    private ExecutorService executorService;//线程池
bubuko.com,布布扣    private final int POOL_SIZE=10;//单个CPU线程池大小
bubuko.com,布布扣    
bubuko.com,布布扣    public MultiThreadServer() throws IOException{
bubuko.com,布布扣        serverSocket=new ServerSocket(port);
bubuko.com,布布扣        //Runtime的availableProcessor()方法返回当前系统的CPU数目.
bubuko.com,布布扣        executorService=Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
bubuko.com,布布扣        System.out.println("服务器启动");
bubuko.com,布布扣    }
bubuko.com,布布扣    
bubuko.com,布布扣    public void service(){
bubuko.com,布布扣        while(true){
bubuko.com,布布扣            Socket socket=null;
bubuko.com,布布扣            try {
bubuko.com,布布扣                //接收客户连接,只要客户进行了连接,就会触发accept();从而建立连接
bubuko.com,布布扣                socket=serverSocket.accept();
bubuko.com,布布扣                executorService.execute(new Handler(socket));
bubuko.com,布布扣                
bubuko.com,布布扣            } catch (Exception e) {
bubuko.com,布布扣                e.printStackTrace();
bubuko.com,布布扣            }
bubuko.com,布布扣        }
bubuko.com,布布扣    }
bubuko.com,布布扣    
bubuko.com,布布扣    public static void main(String[] args) throws IOException {
bubuko.com,布布扣        new MultiThreadServer().service();
bubuko.com,布布扣    }
bubuko.com,布布扣
bubuko.com,布布扣}
bubuko.com,布布扣
bubuko.com,布布扣class Handler implements Runnable{
bubuko.com,布布扣    private Socket socket;
bubuko.com,布布扣    public Handler(Socket socket){
bubuko.com,布布扣        this.socket=socket;
bubuko.com,布布扣    }
bubuko.com,布布扣    private PrintWriter getWriter(Socket socket) throws IOException{
bubuko.com,布布扣        OutputStream socketOut=socket.getOutputStream();
bubuko.com,布布扣        return new PrintWriter(socketOut,true);
bubuko.com,布布扣    }
bubuko.com,布布扣    private BufferedReader getReader(Socket socket) throws IOException{
bubuko.com,布布扣        InputStream socketIn=socket.getInputStream();
bubuko.com,布布扣        return new BufferedReader(new InputStreamReader(socketIn));
bubuko.com,布布扣    }
bubuko.com,布布扣    public String echo(String msg){
bubuko.com,布布扣        return "echo:"+msg;
bubuko.com,布布扣    }
bubuko.com,布布扣    public void run(){
bubuko.com,布布扣        try {
bubuko.com,布布扣            System.out.println("New connection accepted "+socket.getInetAddress()+":"+socket.getPort());             BufferedReader br=getReader(socket);             PrintWriter pw=getWriter(socket);             String msg=null;             while((msg=br.readLine())!=null){                 System.out.println(msg);                 pw.println(echo(msg));                 if(msg.equals("bye"))                     break;             }         } catch (IOException e) {             e.printStackTrace();         }finally{             try {                 if(socket!=null)                     socket.close();             } catch (IOException e) {                 e.printStackTrace();             }         }     } }


2.客户端

bubuko.com,布布扣package sterning;
bubuko.com,布布扣
bubuko.com,布布扣import java.io.BufferedReader;
bubuko.com,布布扣import java.io.IOException;
bubuko.com,布布扣import java.io.InputStreamReader;
bubuko.com,布布扣import java.io.OutputStream;
bubuko.com,布布扣import java.net.Socket;
bubuko.com,布布扣import java.util.concurrent.ExecutorService;
bubuko.com,布布扣import java.util.concurrent.Executors;
bubuko.com,布布扣
bubuko.com,布布扣public class MultiThreadClient {
bubuko.com,布布扣    
bubuko.com,布布扣    public static void main(String[] args) {
bubuko.com,布布扣        int numTasks = 10;
bubuko.com,布布扣        
bubuko.com,布布扣        ExecutorService exec = Executors.newCachedThreadPool();
bubuko.com,布布扣
bubuko.com,布布扣        for (int i = 0; i < numTasks; i++{
bubuko.com,布布扣            exec.execute(createTask(i));
bubuko.com,布布扣        }
bubuko.com,布布扣
bubuko.com,布布扣    }
bubuko.com,布布扣
bubuko.com,布布扣    // 定义一个简单的任务
bubuko.com,布布扣    private static Runnable createTask(final int taskID) {
bubuko.com,布布扣        return new Runnable() {
bubuko.com,布布扣            private Socket socket = null;
bubuko.com,布布扣            private int port=8821;
bubuko.com,布布扣
bubuko.com,布布扣            public void run() {
bubuko.com,布布扣                System.out.println("Task " + taskID + ":start");
bubuko.com,布布扣                try {                    
bubuko.com,布布扣                    socket = new Socket("localhost", port);
bubuko.com,布布扣                    // 发送关闭命令
bubuko.com,布布扣                    OutputStream socketOut = socket.getOutputStream();
bubuko.com,布布扣                    socketOut.write("shutdown\r\n".getBytes());
bubuko.com,布布扣
bubuko.com,布布扣                    // 接收服务器的反馈
bubuko.com,布布扣                    BufferedReader br = new BufferedReader(
bubuko.com,布布扣                            new InputStreamReader(socket.getInputStream()));
bubuko.com,布布扣                    String msg = null;
bubuko.com,布布扣                    while ((msg = br.readLine()) != null)
bubuko.com,布布扣                        System.out.println(msg);
bubuko.com,布布扣                } catch (IOException e) {                    
bubuko.com,布布扣                    e.printStackTrace();
bubuko.com,布布扣                }
bubuko.com,布布扣            }
bubuko.com,布布扣
bubuko.com,布布扣        };
bubuko.com,布布扣    }
bubuko.com,布布扣}
bubuko.com,布布扣


从而实现了多个客户端向服务器端发送请求,服务器端采用多线程的方式来处理的情况.再结合我之前的例子---Java基于Socket文件传输示例,就可以实现多线程文件的传输了

多线程Java Socket编程示例(转)

标签:style   blog   http   io   color   ar   os   sp   java   

原文地址:http://www.cnblogs.com/sandea/p/4102572.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!