Home Java javaTutorial Java multi-threading implements communication between server and multiple clients

Java multi-threading implements communication between server and multiple clients

Jan 05, 2017 pm 03:23 PM

Use java language to build a network server to realize communication between the client and the server, so that the client has independent threads and does not interfere with each other.

Basic steps for applying multi-threading to realize communication between servers and multi-threads

The server creates a ServerSocket and calls accept() in a loop to wait for the client connection

The client creates a Socket and requests a connection with the server.

The server accepts the client's request and creates a socekt to establish a dedicated connection with the client.

The socket to establish the link is on a separate thread Dialogue

The server continues to wait for new links

Server-side Server.java

package test.concurrent.socket; 
  
import java.io.*; 
import java.net.InetAddress; 
import java.net.ServerSocket; 
import java.net.Socket; 
  
/** 
 * Created by dong on 15-6-22. 
 * 基于TCP协议的Socket通信,实现用户登录 
 * 服务器端 
 */
public class Server { 
  
  public static void main(String[] args) { 
  
    try { 
      //1、创建一个服务器端Socket,即ServerSocket, 指定绑定的端口,并监听此端口 
      ServerSocket serverSocket = new ServerSocket(8888); 
      Socket socket = null; 
      //记录客户端的数量 
      int count = 0; 
      System.out.println("***服务器即将启动,等待客户端的链接***"); 
      //循环监听等待客户端的链接 
      while (true){ 
        //调用accept()方法开始监听,等待客户端的链接 
        socket = serverSocket.accept(); 
        //创建一个新的线程 
        ServerThread serverThread = new ServerThread(socket); 
        //启动线程 
        serverThread.start(); 
  
        count++; //统计客户端的数量 
        System.out.println("客户端的数量: " + count); 
        InetAddress address = socket.getInetAddress(); 
        System.out.println("当前客户端的IP : " + address.getHostAddress()); 
      } 
  
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
}
Copy after login

Server-side thread processing class ServerThread.java

package test.concurrent.socket; 
  
import java.io.*; 
import java.net.Socket; 
  
/** 
 * Created by dong on 15-6-22. 
 * 服务器端线程处理类 
 */
public class ServerThread extends Thread { 
  
  //和本线程相关的Socket 
  Socket socket = null; 
  public ServerThread(Socket socket){ 
    this.socket = socket; 
  } 
  
  //线程执行的操作,响应客户端的请求 
  public void run(){ 
  
    InputStream is = null; 
    InputStreamReader isr = null; 
    BufferedReader br = null; 
  
    OutputStream os = null; 
    PrintWriter pw = null; 
    try { 
  
      //获取一个输入流,并读取客户端的信息 
      is = socket.getInputStream(); 
      isr = new InputStreamReader(is); //将字节流转化为字符流 
      br = new BufferedReader(isr); //添加缓冲 
      String info = null; 
      //循环读取数据 
      while ((info = br.readLine()) != null){ 
        System.out.println("我是服务器,客户端说: " +info); 
      } 
  
      socket.shutdownInput(); //关闭输入流 
  
      //获取输出流,响应客户端的请求 
      os = socket.getOutputStream(); 
      pw = new PrintWriter(os); //包装为打印流 
      pw.write("欢迎你"); 
      pw.flush(); //将缓存输出 
  
  
    } catch (IOException e) { 
      e.printStackTrace(); 
    }finally { 
  
  
        try { 
          //关闭资源 
          if (pw != null) 
            pw.close(); 
          if (os != null) 
            os.close(); 
          if (is != null) 
            is.close(); 
          if (isr != null) 
            isr.close(); 
          if (br != null) 
            br.close(); 
          if (socket != null) 
            socket.close(); 
        } catch (IOException e) { 
          e.printStackTrace(); 
  
        } 
  
    } 
  
  
  
  } 
}
Copy after login

Client Client. java

package test.concurrent.socket; 
  
import java.io.*; 
import java.net.Socket; 
  
/** 
 * Created by dong on 15-6-22. 
 * 客户端 
 */
public class Client { 
  
  public static void main(String[] args) { 
  
    try { 
      //1、创建客户端Socket,指定服务器端口号和地址 
      Socket socket = new Socket("localhost",8888); 
      //2、获取输出流,向服务器发送信息 
      OutputStream os = socket.getOutputStream(); //字节输出流 
      PrintWriter pw = new PrintWriter(os); //将输出流包装为打印流 
      pw.write("用户名:tom; 密码:456"); 
      pw.flush(); 
      socket.shutdownOutput(); //关闭输出流 
  
      InputStream is = socket.getInputStream(); 
      InputStreamReader isr = new InputStreamReader(is); 
      BufferedReader br = new BufferedReader(isr); 
  
      String info = null; 
      //循环读取 
      while ((info = br.readLine()) != null){ 
        System.out.println("我是客户端:服务器说:" + info); 
      } 
  
      br.close(); 
      is.close(); 
      isr.close(); 
  
  
      pw.close(); 
      os.close(); 
      socket.close(); 
    } catch (IOException e) { 
      e.printStackTrace(); 
    } 
  } 
}
Copy after login

The above is the entire content of this article. I hope it will be helpful to everyone's learning. I also hope that everyone will support the PHP Chinese website.

For more articles related to Java multi-threading to implement communication between the server and multiple clients, please pay attention to the PHP Chinese website!


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Is the company's security software causing the application to fail to run? How to troubleshoot and solve it? Apr 19, 2025 pm 04:51 PM

Troubleshooting and solutions to the company's security software that causes some applications to not function properly. Many companies will deploy security software in order to ensure internal network security. ...

How to simplify field mapping issues in system docking using MapStruct? How to simplify field mapping issues in system docking using MapStruct? Apr 19, 2025 pm 06:21 PM

Field mapping processing in system docking often encounters a difficult problem when performing system docking: how to effectively map the interface fields of system A...

How to elegantly obtain entity class variable names to build database query conditions? How to elegantly obtain entity class variable names to build database query conditions? Apr 19, 2025 pm 11:42 PM

When using MyBatis-Plus or other ORM frameworks for database operations, it is often necessary to construct query conditions based on the attribute name of the entity class. If you manually every time...

How do I convert names to numbers to implement sorting and maintain consistency in groups? How do I convert names to numbers to implement sorting and maintain consistency in groups? Apr 19, 2025 pm 11:30 PM

Solutions to convert names to numbers to implement sorting In many application scenarios, users may need to sort in groups, especially in one...

How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? How does IntelliJ IDEA identify the port number of a Spring Boot project without outputting a log? Apr 19, 2025 pm 11:45 PM

Start Spring using IntelliJIDEAUltimate version...

How to safely convert Java objects to arrays? How to safely convert Java objects to arrays? Apr 19, 2025 pm 11:33 PM

Conversion of Java Objects and Arrays: In-depth discussion of the risks and correct methods of cast type conversion Many Java beginners will encounter the conversion of an object into an array...

E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? E-commerce platform SKU and SPU database design: How to take into account both user-defined attributes and attributeless products? Apr 19, 2025 pm 11:27 PM

Detailed explanation of the design of SKU and SPU tables on e-commerce platforms This article will discuss the database design issues of SKU and SPU in e-commerce platforms, especially how to deal with user-defined sales...

How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? How to elegantly get entity class variable name building query conditions when using TKMyBatis for database query? Apr 19, 2025 pm 09:51 PM

When using TKMyBatis for database queries, how to gracefully get entity class variable names to build query conditions is a common problem. This article will pin...

See all articles