java socket 通訊socketServer 服務端多執行緒

markriver發表於2021-09-09

執行緒程式碼

    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

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 {
            // 3.獲取輸入流,並讀取客服端資訊
            is = socket.getInputStream();//位元組輸入流
            isr = new InputStreamReader(is);//將位元組流轉換為字元流
            br = new BufferedReader(isr);//為輸入流新增緩衝
            String info = null;
            String infoResult = "";
            String sendString="";
            while ((info=br.readLine())!=null) {//迴圈讀取客服端的資訊

                infoResult = infoResult+info;

            }

            socket.shutdownInput();//關閉輸入流

            //=====================================================

            System.out.println(" In:"+infoResult);

            // 4.響應客服端  即給客服端傳送資訊
            os = socket.getOutputStream();//位元組輸出流
            pw = new PrintWriter(os);//將輸出流包裝為列印流
            //sendString = Integer.toString(BiaoQian);  

            pw.write(sendString);//  寫入客戶端的資訊+只能是純數字字串
            System.out.println("Out:"+sendString);          
            pw.flush();//呼叫flush()方法將緩衝輸出
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally{
            try {
                // 5.關閉資源
                if (pw!=null) {pw.close();}
                if (os!=null) {os.close();}
                if (br!=null) {br.close();}
                if (isr!=null) {isr.close();}
                if (is!=null) {is.close();  }
                if (socket!=null) {socket.close();}

            } catch (Exception e2) {
                // TODO: handle exception
            }

        }

    }

}

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

相關文章