JAVA并发处理经验(四)并行模式与算法6:socket的服务端多线程

一、前言

关于网络编程,这一章一般用NIO编程,但是我们得一步步,免得扯着蛋蛋。我们先温习一下,socket的服务器---客户端;我们适用服务端用线程池,线程池没有懂得小火炮,看以前的,或者直接问群里就ok。

二、socket服务端多线程

友情提示:可以用spring或者注解线程池,在实际运用的时候;

2.1 socket线程池实现客户端

package pattern.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created by ycy on 16/1/18.
 */
public class MultiThreadEchoserver {
    private static ExecutorService tp = Executors.newCachedThreadPool();

    static class HandleMsg implements Runnable {
        Socket clientSocket;

        public HandleMsg(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        public void run() {
            BufferedReader is = null;
            PrintWriter os = null;
            try {
                is = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
                  os=new PrintWriter(clientSocket.getOutputStream(),true);
                //从inputstream 中读取客户端发送的数据

                String inputString =null;
                long b = System.currentTimeMillis();
                while ((inputString = is.readLine()) != null) {
                    System.out.println("搜到客户端数据"+inputString);
                    os.println(inputString+"--来自服务端");
                }
                long e = System.currentTimeMillis();
                System.out.println("spend:" + (e - b) + "ms");
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

                try {
                    if (is != null) {
                        is.close();
                    }
                    if (os != null) {
                        os.close();
                    }
                    clientSocket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }

            }
        }
    }

    public static void main(String[] args) {

        ServerSocket serverSocke = null;
        Socket clientSocket = null;
        try {
            serverSocke = new ServerSocket(65500);
        } catch (IOException e) {
            e.printStackTrace();
        }
        while (true) {
            try {
                clientSocket = serverSocke.accept();
                System.out.println(clientSocket.getRemoteSocketAddress() + " conect");
                tp.execute(new HandleMsg(clientSocket));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

2.2 socke客户端

注意里面注解:巨坑

package pattern.nio;

import java.io.*;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Created by ycy on 16/1/18.
 */
public class Client {
    public static void main(String[] args) throws IOException {
        Socket client=null;
        PrintWriter writer=null;
        BufferedReader reader=null;
        try {
            client=new Socket();
            client.connect(new InetSocketAddress("127.0.0.1",65500));
            writer=new PrintWriter(client.getOutputStream(),true);
            OutputStream os=client.getOutputStream();
            String secondeString="这个是通过os传送得---";
            os.write(secondeString.getBytes());
            //巨坑:如果你服务端口用readline来读取,客户端用print 来写入数据,那么客户端就一直不能关闭.不信你试一试
            writer.printf("hello");
            writer.flush();

            reader=new BufferedReader(new InputStreamReader(client.getInputStream()));
            System.out.println("from serverL:"+reader.readLine());

        }catch (UnknownHostException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }finally {
            if (writer!=null){
                writer.close();
            }
            if (reader!=null){
                reader.close();
            }
            if (client!=null){
                client.close();
            }
        }
    }
}

2.3 高io的客户端

package pattern.nio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.LockSupport;

/**
 * Created by ycy on 16/1/19.
 * 这个适用LockSupport阻塞当前线程模拟
 * io耗时的情况,服务器响应就慢了;
 * 在其他语言里面,所以不要这么用,这么用就显得逼格不高了.就像生产者-消费者一样,高逼格都是用队列服务器了
 *
 */
public class HeavySocketClient {
    private static ExecutorService tp = Executors.newCachedThreadPool();
    private static final int sleep_time = 1000 * 1000 * 1000;

    public static class EchoClient implements Runnable {
        public void run() {
            Socket client = null;
            PrintWriter writer = null;
            BufferedReader reader = null;
            try {
                client = new Socket();
                client.connect(new InetSocketAddress("127.0.0.1", 65500));
                writer = new PrintWriter(client.getOutputStream(), true);
                writer.print("high client");
                LockSupport.parkNanos(sleep_time);
                writer.print("end client1");
                LockSupport.parkNanos(sleep_time);
                writer.print("end client2");
                LockSupport.parkNanos(sleep_time);
                writer.print("end client3");
                LockSupport.parkNanos(sleep_time);
                writer.print("end client4");
                LockSupport.parkNanos(sleep_time);
                writer.print("end client5");
                LockSupport.parkNanos(sleep_time);
                writer.print("end client6");
                writer.println();
                writer.flush();
                reader = new BufferedReader(new InputStreamReader(client.getInputStream()));
                System.out.println("from server:" + reader.readLine());
            } catch (UnknownHostException  e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {

                try {

                    if (writer != null) {
                        writer.close();
                    }
                    if (reader != null) {
                        reader.close();
                    }
                    if (client != null) {
                        client.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }
    }

    public static void main(String[] args) {
        EchoClient ec=new EchoClient();
        for (int i = 0; i <10 ; i++) {
            tp.submit(ec);
        }
    }
}

三、预告 

本身就不熟悉的socket服务,看起来还是不尽人意。你不熟悉,并不是因为你差,是因为这个市场需要这个少。呵呵。 那么未来解决io慢得情况,我们适用NIO编辑,这个才是网络编程的实用点哦

你可能感兴趣的:(JAVA并发处理经验(四)并行模式与算法6:socket的服务端多线程)