- import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- /**
- * Socket監聽服務器
- * @author guishuanglin 2008-11-3
- *
- */
- public class SocketListenServe implements Runnable{
- private ServerSocket ss;
- private boolean listening = true;
- private int port = 10001;
- //最大隊列長度被設置爲 backlog 參數
- private int backlog = 20;
- private Class client;
- //讀取客戶端數據本地緩衝
- private int cacheBtye=1024;
- private int requestCount=100000;
- public SocketListenServe(IProcessClientData pClient) {
- client = pClient.getClass();
- }
- public SocketListenServe(int cacheBtye,IProcessClientData pClient) {
- this.cacheBtye = cacheBtye;
- client = pClient.getClass();
- }
- public SocketListenServe(int port,int backlog,int cacheBtye,IProcessClientData pClient) {
- this.port = port;
- this.backlog = backlog;
- this.cacheBtye = cacheBtye;
- client = pClient.getClass();
- }
- public void run() {
- Init();// 初始化
- Listen();// 啓動監聽
- }
- /**
- * 初始化
- * @date 2008-11-3
- */
- public void Init() {
- try {
- ss = new ServerSocket(port, backlog);
- System.out.println("服務已經啓動,開始在端口["+port+"]監聽,等待TCP客戶端連接....");
- } catch (IOException ie) {
- System.out.println("無法啓動監聽,可能由於網絡不通,或端口["+port+"]已被佔用.");
- ie.printStackTrace();
- System.exit(0);
- }
- }
- /**
- * 啓動監聽
- * @date 2008-11-3
- */
- public void Listen() {
- while (listening) {
- try {
- Socket s = ss.accept();
- System.out.println("收到客戶端["+ s.getInetAddress().getHostAddress() + "]連接請求.");
- new Thread(new ProcessRequest(s,this.getRequestCount(),cacheBtye,client)).start();
- } catch (IOException ie) {
- System.out.println("服務器異常");
- ie.printStackTrace();
- //碰到異常關閉服務重新打開
- this.ReleaseResource();
- this.Init();
- }catch (Exception ex) {
- System.out.println("服務器異常");
- ex.printStackTrace();
- this.ReleaseResource();
- this.Init();
- }
- }
- }
- /**
- * 關閉服務實例
- * @date 2008-11-3
- */
- public void ReleaseResource(){
- try {
- if (ss != null && !ss.isClosed())
- ss.close();
- //關閉服務後睡眠5s.
- Thread.sleep(5000);
- } catch (IOException e) {
- e.printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- public int getRequestCount(){
- //重複計數
- if(this.requestCount >1000000){
- this.requestCount=0;
- }
- return this.requestCount++;
- }
- public static void main(String args[]) {
- //ProcessClientDataImpl client = new ProcessClientDataImpl();
- //SocketListenServe servie = new SocketListenServe(client);
- }
- }
jdk1.4 構建 java多線程,併發設計框架 使用列子(一)
網絡 Socket監聽服務器
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.