Socket网络编程的应用-多线程

Java 网络编程(超级详细)

一.基础的通信模式

服务器端

public class SocketServer {
   public static void main(String[] args) throws IOException, InterruptedException {
       ServerSocket serverSocket = new ServerSocket(8080);
       System.out.println("服务器端服务开启...");


       while (true){

           Socket socket = serverSocket.accept();//阻塞等待

           InputStream inputStream = socket.getInputStream();

           StringBuilder builder=new StringBuilder();

           byte[] bytes=new byte[1024];
           while (true){
               int len = inputStream.read(bytes);
               if (len==-1) break;
               builder.append(new String(bytes,0,len));
           }
           System.out.println("收到服务器端的内容:"+builder.toString());

           socket.shutdownInput();//表示当前输入流完成

           //处理数据
           Thread.sleep(1000);//模拟数据处理需要的时间
           //服务器响应
           OutputStream outputStream = socket.getOutputStream();
           outputStream.write("数据处理完毕".getBytes());

           socket.shutdownOutput();//此次数据返回结束
       }

   }

}

客户端

public class SocketClient {
   public static void main(String[] args) throws IOException {


       for (int i = 0; i < 10; i++) {
           Socket socket=new Socket("localhost",8080);

           System.out.println("向服务器端发送数据:");
           //发送信息到服务器端
           OutputStream outputStream = socket.getOutputStream();

           outputStream.write(("你好服务器"+i).getBytes());

           socket.shutdownOutput();//表示关闭了流

           //接受服务器端的响应
           InputStream inputStream = socket.getInputStream();

           StringBuilder builder=new StringBuilder();

           byte[] bytes=new byte[1024];

           while (true){
               int len = inputStream.read(bytes);
               if (len==-1) break;
               builder.append(new String(bytes,0,len));
           }

           System.out.println("接收到响应:"+builder.toString());

           socket.shutdownInput();//此次接收数据结束
       }

   }
}

二.基础通信封装过滤流

服务器端

public class SocketServer {
   public static void main(String[] args) throws IOException, InterruptedException {
       ServerSocket serverSocket = new ServerSocket(8080);
       System.out.println("服务器端服务开启...");


       while (true){

           Socket socket = serverSocket.accept();//阻塞等待

           InputStream inputStream = socket.getInputStream();

           DataInputStream dataInputStream = new DataInputStream(inputStream);

           System.out.println("收到服务器端的内容:"+dataInputStream.readUTF());

           socket.shutdownInput();//表示当前输入流完成

           //处理数据
           Thread.sleep(1000);//模拟数据处理需要的时间
           //服务器响应
           OutputStream outputStream = socket.getOutputStream();

           DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

           dataOutputStream.writeUTF(Thread.currentThread().getName()+"线程,数据处理完毕");

           dataOutputStream.flush();

           socket.shutdownOutput();//此次数据返回结束
       }

   }

}

客户端

public class SocketClient {
   public static void main(String[] args) throws IOException {


       for (int i = 0; i < 10; i++) {
           Socket socket=new Socket("localhost",8080);

           //发送信息到服务器端
           OutputStream outputStream = socket.getOutputStream();

           DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

           dataOutputStream.writeUTF("你好服务器"+i);

           dataOutputStream.flush();

           socket.shutdownOutput();//表示关闭了流

           //接受服务器端的响应
           InputStream inputStream = socket.getInputStream();

           DataInputStream dataInputStream = new DataInputStream(inputStream);

           System.out.println("接收到响应:"+dataInputStream.readUTF());

           socket.shutdownInput();//此次接收数据结束
       }

   }
}

三.基础通信支持多线程

每次请求开启一个线程

服务器端

这样做存在的问题有每一次请求都会创建一个线程池,这样就会很消耗内存,与系统资源。

public class SocketServer {
   public static void main(String[] args) throws IOException, InterruptedException {
       ServerSocket serverSocket = new ServerSocket(8080);
       System.out.println("服务器端服务开启...");

       while (true){

           Socket socket = serverSocket.accept();//阻塞等待

           new Thread(new Runnable() {
               @Override
               public void run() {
                   try {
                       InputStream inputStream = socket.getInputStream();

                       DataInputStream dataInputStream = new DataInputStream(inputStream);

                       System.out.println("收到服务器端的内容:"+dataInputStream.readUTF());

                       socket.shutdownInput();//表示当前输入流完成

                       //处理数据
                       System.out.println(Thread.currentThread().getName()+"正在处理请求...");
                       Thread.sleep(1000);//模拟数据处理需要的时间
                       //服务器响应
                       OutputStream outputStream = socket.getOutputStream();

                       DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

                       dataOutputStream.writeUTF(Thread.currentThread().getName()+"线程,数据处理完毕");

                       dataOutputStream.flush();

                       socket.shutdownOutput();//此次数据返回结束
                   }catch (Exception e){
                       e.printStackTrace();
                   }
               }
           }).start();

       }

   }

}

线程池解决

可以很好的解决线程复用的问题

public class SocketServer {
   public static void main(String[] args) throws IOException, InterruptedException {
       ServerSocket serverSocket = new ServerSocket(8080);
       System.out.println("服务器端服务开启...");

       //创建线程池
       ExecutorService fixedThreadPool = Executors.newFixedThreadPool(5);
       while (true){

           Socket socket = serverSocket.accept();//阻塞等待

           fixedThreadPool.submit(new Runnable() {
               @Override
               public void run() {
                   try {
                       InputStream inputStream = socket.getInputStream();

                       DataInputStream dataInputStream = new DataInputStream(inputStream);

                       System.out.println("收到服务器端的内容:"+dataInputStream.readUTF());

                       socket.shutdownInput();//表示当前输入流完成

                       //处理数据
                       System.out.println(Thread.currentThread().getName()+"正在处理请求...");
                       //Thread.sleep(1000);//模拟数据处理需要的时间
                       //服务器响应
                       OutputStream outputStream = socket.getOutputStream();

                       DataOutputStream dataOutputStream = new DataOutputStream(outputStream);

                       dataOutputStream.writeUTF(Thread.currentThread().getName()+"线程,数据处理完毕");

                       dataOutputStream.flush();

                       socket.shutdownOutput();//此次数据返回结束
                   }catch (Exception e){
                       e.printStackTrace();
                   }
               }
           });

       }

   }

}

你可能感兴趣的:(Java开发,网络,java,服务器)