本文共 2240 字,大约阅读时间需要 7 分钟。
网络
Socket监听服务器 - import java.io.IOException;
- import java.net.ServerSocket;
- import java.net.Socket;
- public class SocketListenServe implements Runnable{
- private ServerSocket ss;
- private boolean listening = true;
- private int port = 10001;
-
- 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();
- }
-
- 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);
- }
- }
-
- 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();
- }
- }
- }
-
- public void ReleaseResource(){
- try {
- if (ss != null && !ss.isClosed())
- ss.close();
-
- 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[]) {
-
-
- }
- }
转载地址:http://ycnmd.baihongyu.com/