search
HomeJavajavaTutorialJava multi-threading implements communication between server and multiple clients

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(); 
    } 
  } 
}

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(); 
  
        } 
  
    } 
  
  
  
  } 
}

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(); 
    } 
  } 
}

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
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
What are some strategies for mitigating platform-specific issues in Java applications?What are some strategies for mitigating platform-specific issues in Java applications?May 01, 2025 am 12:20 AM

How does Java alleviate platform-specific problems? Java implements platform-independent through JVM and standard libraries. 1) Use bytecode and JVM to abstract the operating system differences; 2) The standard library provides cross-platform APIs, such as Paths class processing file paths, and Charset class processing character encoding; 3) Use configuration files and multi-platform testing in actual projects for optimization and debugging.

What is the relationship between Java's platform independence and microservices architecture?What is the relationship between Java's platform independence and microservices architecture?May 01, 2025 am 12:16 AM

Java'splatformindependenceenhancesmicroservicesarchitecturebyofferingdeploymentflexibility,consistency,scalability,andportability.1)DeploymentflexibilityallowsmicroservicestorunonanyplatformwithaJVM.2)Consistencyacrossservicessimplifiesdevelopmentand

How does GraalVM relate to Java's platform independence goals?How does GraalVM relate to Java's platform independence goals?May 01, 2025 am 12:14 AM

GraalVM enhances Java's platform independence in three ways: 1. Cross-language interoperability, allowing Java to seamlessly interoperate with other languages; 2. Independent runtime environment, compile Java programs into local executable files through GraalVMNativeImage; 3. Performance optimization, Graal compiler generates efficient machine code to improve the performance and consistency of Java programs.

How do you test Java applications for platform compatibility?How do you test Java applications for platform compatibility?May 01, 2025 am 12:09 AM

ToeffectivelytestJavaapplicationsforplatformcompatibility,followthesesteps:1)SetupautomatedtestingacrossmultipleplatformsusingCItoolslikeJenkinsorGitHubActions.2)ConductmanualtestingonrealhardwaretocatchissuesnotfoundinCIenvironments.3)Checkcross-pla

What is the role of the Java compiler (javac) in achieving platform independence?What is the role of the Java compiler (javac) in achieving platform independence?May 01, 2025 am 12:06 AM

The Java compiler realizes Java's platform independence by converting source code into platform-independent bytecode, allowing Java programs to run on any operating system with JVM installed.

What are the advantages of using bytecode over native code for platform independence?What are the advantages of using bytecode over native code for platform independence?Apr 30, 2025 am 12:24 AM

Bytecodeachievesplatformindependencebybeingexecutedbyavirtualmachine(VM),allowingcodetorunonanyplatformwiththeappropriateVM.Forexample,JavabytecodecanrunonanydevicewithaJVM,enabling"writeonce,runanywhere"functionality.Whilebytecodeoffersenh

Is Java truly 100% platform-independent? Why or why not?Is Java truly 100% platform-independent? Why or why not?Apr 30, 2025 am 12:18 AM

Java cannot achieve 100% platform independence, but its platform independence is implemented through JVM and bytecode to ensure that the code runs on different platforms. Specific implementations include: 1. Compilation into bytecode; 2. Interpretation and execution of JVM; 3. Consistency of the standard library. However, JVM implementation differences, operating system and hardware differences, and compatibility of third-party libraries may affect its platform independence.

How does Java's platform independence support code maintainability?How does Java's platform independence support code maintainability?Apr 30, 2025 am 12:15 AM

Java realizes platform independence through "write once, run everywhere" and improves code maintainability: 1. High code reuse and reduces duplicate development; 2. Low maintenance cost, only one modification is required; 3. High team collaboration efficiency is high, convenient for knowledge sharing.

See all articles

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

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),