中国大数据教育领跑者

IT培训上市机构

您现在的位置:首页 > Java培训 > java项目案例>Java如何创建多线程服务器?

Java如何创建多线程服务器?

2017-12-22 10:17:29 作者:魔据大数据学院

在Java编程中,如何创建多线程服务器?

以下示例演示如何使用ServerSocket类的MultiThreadServer(socketname)方法和Socket类的ssock.accept()方法来创建多线程服务器。

package com.yiibai;  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(8806);       System.out.println("Server Start and 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);       }    } } 
Java

上述代码示例将产生以下结果 -

Server Start and Listening: 
Shell

示例-2

以下是如何创建多线程服务器的另一个示例。

package com.yiibai;  import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter;  import java.net.ServerSocket; import java.net.Socket; import java.text.SimpleDateFormat; import java.util.Calendar;  public class MultiThreadServer2 {     ServerSocket myServerSocket;     boolean ServerOn = true;      public MultiThreadServer2() {        try {          myServerSocket = new ServerSocket(12345);       } catch(IOException ioe) {           System.out.println("Could not create server socket on port 12345. Quitting.");          System.exit(-1);       }         Calendar now = Calendar.getInstance();       SimpleDateFormat formatter = new SimpleDateFormat(          "yyyy/MM/dd \'at\' hh:mm:ss ");       System.out.println("It is now : " + formatter.format(now.getTime()));        while(ServerOn) {           try {              Socket clientSocket = myServerSocket.accept();             ClientServiceThread cliThread = new ClientServiceThread(clientSocket);             cliThread.start();           } catch(IOException ioe) {              System.out.println("Exception found on accept. Ignoring. Stack Trace :");              ioe.printStackTrace();           }         }        try {           myServerSocket.close();           System.out.println("Server Stopped");        } catch(Exception ioe) {           System.out.println("Error Found stopping server socket");           System.exit(-1);        }     }      public static void main(String[] args) {         new MultiThreadServer2();     }      class ClientServiceThread extends Thread {         Socket myClientSocket;         boolean m_bRunThread = true;          public ClientServiceThread() {             super();         }          ClientServiceThread(Socket s) {             myClientSocket = s;         }          public void run() {             BufferedReader in = null;             PrintWriter out = null;             System.out.println("Accepted Client Address - " + myClientSocket.getInetAddress().getHostName());             try {                 in = new BufferedReader(new InputStreamReader(myClientSocket.getInputStream()));                 out = new PrintWriter(new OutputStreamWriter(myClientSocket.getOutputStream()));                  while (m_bRunThread) {                     String clientCommand = in.readLine();                     System.out.println("Client Says :" + clientCommand);                      if (!ServerOn) {                         System.out.print("Server has already stopped");                         out.println("Server has already stopped");                         out.flush();                         m_bRunThread = false;                     }                     if (clientCommand.equalsIgnoreCase("quit")) {                         m_bRunThread = false;                         System.out.print("Stopping client thread for client : ");                     } else if (clientCommand.equalsIgnoreCase("end")) {                         m_bRunThread = false;                         System.out.print("Stopping client thread for client : ");                         ServerOn = false;                     } else {                         out.println("Server Says : " + clientCommand);                         out.flush();                     }                 }             } catch (Exception e) {                 e.printStackTrace();             } finally {                 try {                     in.close();                     out.close();                     myClientSocket.close();                     System.out.println("...Stopped");                 } catch (IOException ioe) {                     ioe.printStackTrace();                 }             }         }     } } 
Java

上述代码示例将产生以下结果 -

 

It is now : 2017/09/20 at 10:45:19 
Shell
package com.yiibai;  import java.io.IOException; import java.net.InetAddress; import java.net.Socket; import java.net.SocketException; import java.net.UnknownHostException;  public class SocketClient {     public static void main(String[] args) {         try {             //InetAddress addr = InetAddress.getByName("127.0.0.1");             Socket theSocket = new Socket("127.0.0.1", 12345);             System.out.println("Connected to " + theSocket.getInetAddress() + " on port " + theSocket.getPort()                     + " from port " + theSocket.getLocalPort() + " of " + theSocket.getLocalAddress());         } catch (UnknownHostException e) {             System.err.println("I can't find " + e);         } catch (SocketException e) {             System.err.println("Could not connect to " + e);         } catch (IOException e) {             System.err.println(e);         }     } } 
Java

 

相关推荐
[免责声明]本文来源于网络转载,仅供学习交流使用,不构成商业目的。版权归原作者所有,如涉及作品内容、版权和其它问题请在30日内与本网联系,我们将在第一时进行处理

值班手机:18501996998

咨询QQ: 226594285 / 428683440

校区地址:北京市海淀区中关村科技园首农蓝海中心C座-7层

全国咨询热线:400-690-5006

点击关注:

魔据教育官方微博

魔据官方微信