Java實現多執行緒區域網聊天室

專注的阿熊發表於2021-06-21

package TCP;

import java.io.IOException;

import java.io.InputStream;

import java.net.ServerSocket;

import java.net.Socket;

import java.util.Scanner;

public class TCPserver2 {

     public static void main(String[] args) {

         Scanner scan = new Scanner(System.in);

         // 例項化具有多執行緒功能的伺服器專用 socket

         // 需要傳遞埠號作為初始化變數

         SuperSocket socket_1 = new SuperSocket(9996);

         SuperSocket socket_2 = new SuperSocket(9998);

         SuperSocket socket_3 = new SuperSocket(9997);

         // 建立三個子執行緒

         Thread s1 = new Thread(socket_1);

         Thread s2 = new Thread(socket_2);

         Thread s3 = new Thread(socket_3);

         try {

             while(true) {

             // 開啟執行緒

                 s1.start();

                 s2.start();

                 s3.start();

                 if(scan.next()=="123"){

                 // 結束執行緒

                     break;

                 }

             }

         } finally {

             try {

             // 關閉套接字

                 socket_1.close();

                 socket_2.close();

                 socket_3.close();

             } catch (IOException e) {

                 e.printStackTrace();

             }

         }

     }

}

class SuperSocket extends Socket implements Runnable{

     InputStream is;

     byte[] buffer;

     Socket socket=null;

     ServerSocket serverSocket=null;

     public SuperSocket(int port){

         try {

         // 初始伺服器型套接字

             serverSocket = 外匯跟單gendan5.comnew ServerSocket(port);

             buffer = new byte[1024];

         } catch (IOException e) {

             e.printStackTrace();

         }

     }

     @Override

     public void run() {

         try {

         // 等待埠連線

             socket = serverSocket.accept();

             // 連線完成後建立輸入流

             is = socket.getInputStream();

             // 讀取客戶端傳送資訊

             int len = is.read(buffer);

             String str = new String(buffer, 0, len);

             System.out.println(str);

         } catch (IOException e) {

             e.printStackTrace();

         }

     }

}

 

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69946337/viewspace-2777652/,如需轉載,請註明出處,否則將追究法律責任。

相關文章