socket使用1

package com.sf.dtx5.request;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.InetAddress;
import java.util.ArrayList;

import com.sf.dtx5.CServer;
import com.sf.dtx5.Config;

/**
 * Socket监听服务线程,处理连接进来的用户
 * 
 */
public class CThreadSocketListen extends CThreadBase {
	/**
	 * 本地IP地址,为防止不同网段的IP连入到服务器
	 */
	private ArrayList<byte[]> LocalIPs = new ArrayList<byte[]>();

	private ServerSocket server;

	/**
	 * Socket计数
	 */
	private static int m_count = 0;

	/**
	 * 取得在线巴枪数
	 * 
	 * @param bIn
	 * @return
	 */
	public static synchronized int getOnlineCount(boolean bIn) {
		if (bIn) {
			m_count++;
		} else {
			if (m_count > 0) {
				m_count--;
			}
		}
		return m_count;
	}

	public CThreadSocketListen(CServer parent) {
		super(parent, 1);
	}

	@Override
	protected void doWorking() {
		Socket client =  null;
		try {
			client = server.accept();
			if (checkClientInSameNet(client)) {
				CThreadSocketWorkingBar s = new CThreadSocketWorkingBar(client);
				s.start();
			} else {
				Config.log.writeLog(3, "过滤外网段的巴枪:%s", client
						.getRemoteSocketAddress().toString());
				client.close();
			}
		} catch (Exception e) {
			Config.log.writeLog(2, "接受命令处理异常CThreadSocketListen line 64:%s", e);
			if (null != client && !client.isClosed()) {
				try {
					client.close();
				} catch (IOException e1) {
					Config.log.writeLog(2, "关闭socket 异常 CThreadSocketListen line 70:%s", e1);
				}
			}
		}
	}

	/**
	 * 检测客户IP是否与服务器IP在同一网段内
	 * 
	 * @param clientip
	 * @return
	 */
	private boolean checkClientInSameNet(Socket client) {
		if (Config.getSocketmustinsamenet()) {
			boolean ipok;
			byte[] serverip;
			byte[] clientip = client.getInetAddress().getAddress();
			for (int i = 0; i < this.LocalIPs.size(); i++) {
				serverip = this.LocalIPs.get(i);
				ipok = true;
				for (int j = 0; j < 3; j++) {
					if (serverip[j] != clientip[j]) {
						ipok = false;
						break;
					}
				}
				if (ipok) {
					return true;
				}
			}
			return false;
		} else {
			return true;
		}
	}

	@Override
	protected boolean onInit() {
		try {
			InetAddress[] ips = InetAddress.getAllByName(InetAddress
					.getLocalHost().getHostName());
			for (int i = 0; i < ips.length; i++) {
				this.LocalIPs.add(ips[i].getAddress());
			}
			server = new ServerSocket(Config.getSocketPort(), 5);
			return true;
		} catch (Exception e) {
			Config.log.writeLog(1, "启动巴枪监听服务失败:%s", e);
		}
		return false;
	}

	@Override
	protected void onClose() {
		try {
			this.server.close();
		} catch (Exception e) {
			Config.log.writeLog(1, "启动巴枪关闭服务失败:%s", e);
		}
	}

}

  

posted @ 2017-12-19 18:18  杯子茶壶  阅读(90)  评论(0)    收藏  举报