Home > Java > javaTutorial > body text

Java example - Socket implements multi-threaded server program

黄舟
Release: 2017-01-20 11:52:05
Original
1239 people have browsed it

The following example demonstrates how to use the accept() method of the Socket class and the MultiThreadServer(socketname) method of the ServerSocket class to implement a multi-threaded server program:

/*
 author by w3cschool.cc
 MultiThreadServer.java
 */import java.io.IOException;import java.io.PrintStream;import java.net.ServerSocket;import java.net.Socket;public class MultiThreadServer implements 
 Runnable {
   Socket csocket;
   MultiThreadServer(Socket csocket) {
      this.csocket = csocket;
   }

   public static void main(String args[]) 
   throws Exception {
      ServerSocket ssock = new ServerSocket(1234);
      System.out.println("Listening");
      while (true) {
         Socket sock = ssock.accept();
         System.out.println("Connected");
         new Thread(new MultiThreadServer(sock)).start();
      }
   }
   public void run() {
      try {
         PrintStream pstream = new PrintStream
         (csocket.getOutputStream());
         for (int i = 100; i >= 0; i--) {
            pstream.println(i + 
            " bottles of beer on the wall");
         }
         pstream.close();
         csocket.close();
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }}
Copy after login

The above code runs the output results For:

Listening
Connected
Copy after login

The above is the content of the Java example-Socket to implement multi-threaded server program. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!