用java写编写的一个GPS源代码请大家多多指教
源代码在线查看: devicetcpservice.java~77~
package com.gps.center.dataservice;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.Document;
import java.io.File;
import org.w3c.dom.NodeList;
import java.net.InetAddress;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SelectionKey;
import java.util.Set;
import java.util.Iterator;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.CharBuffer;
import com.gps.center.baseclass.HashObj;
import com.gps.center.baseclass.MsgObj;
import java.nio.channels.ClosedChannelException;
import com.gps.center.baseclass.ParseData;
/*
*TCP监听类,
*
*
*
*/
public class DeviceTcpService extends ParseData implements Runnable {
private Selector sel = null;
private ServerSocketChannel TerminalTcpServer = null;
private SocketChannel socket = null;
private int centerPort;
private int MaxConnection;
private String centerIP = new String("localhost");
private String CodeType = "GB18030";
public static int sessions = 0;
public DeviceTcpService() {
readxml();
// parseReceiveData = new ParseReceiveData();
//startServer();
}
public synchronized void incsessions() {
sessions++;
}
public synchronized void reducesessions() {
sessions--;
}
public void run() {
System.out.println("Inside startserver");
initializeOperations();
System.out.println("Abt to block on select()");
SelectionKey acceptKey = null;
try {
acceptKey = TerminalTcpServer.register(sel,
SelectionKey.OP_ACCEPT);
} catch (ClosedChannelException ex) {
ex.printStackTrace();
}
try {
while (acceptKey.selector().select() > 0) {
Set readyKeys = sel.selectedKeys();
Iterator it = readyKeys.iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey) it.next();
it.remove();
if (key.isAcceptable()) {
System.out.println("Key is Acceptable");
ServerSocketChannel ssc = (ServerSocketChannel) key.
channel();
socket = (SocketChannel) ssc.accept();
incsessions();
if (sessions > MaxConnection) {
break;
}
socket.configureBlocking(false);
SelectionKey another = socket.register(sel,
SelectionKey.OP_READ |
SelectionKey.OP_WRITE);
}
if (key.isReadable()) {
System.out.println("Key is readable");
String ret = readMessage(key);
if (ret != null) {
if (ret.length() > 1) {
MsgObj msg = new MsgObj();
//cMsgtype:1--TCPMSG,2--DEVICEUDPMSG,3--SMSMSG
//4--TCPSENDTODEVICE,5--UDPSENDTODEVICE,6--SMSSENDTODEVICE,7--TCPSENDTOTERMINAL,8--TCPRETURNTERMINAL
msg.cMsgType = TCPMSG;
msg.cMsg = ret;
msg.cSelectionKey = key;
if (msg.cSelectionKey == null) {
System.out.println(
"msg.cSelectionKey为空DeviceTcpService");
} else {
System.out.println(
"msg.cSelectionKey不为空DeviceTcpService");
}
super.addRecieveMsg(msg);
}
}
else {
System.out.println("终端退出");
while (super.centerMap.containsValue(key)) {
centerMap.remove(key.attachment());
key.cancel();
}
}
}
}
}
} catch (Exception ex1) {
System.err.print(ex1 + "\n");
}
}
public void initializeOperations() {//初始化ServerSocketChannel
try {
sel = Selector.open();
TerminalTcpServer = ServerSocketChannel.open();
TerminalTcpServer.configureBlocking(false);
InetAddress ia = InetAddress.getByName(centerIP);
InetSocketAddress isa = new InetSocketAddress(ia, centerPort);
TerminalTcpServer.socket().bind(isa);
} catch (IOException ex) {
ex.printStackTrace();
}
}
private String readMessage(SelectionKey key) throws IOException {
int nBytes = 0;
String result = null;
socket = (SocketChannel) key.channel();
ByteBuffer buf = ByteBuffer.allocate(512);
try {
nBytes = socket.read(buf);
if (nBytes == -1) {
socket.close();
key.cancel();
reducesessions();
System.out.println("close socketqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq");
}
buf.flip();
Charset charset = Charset.forName(CodeType);
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer = decoder.decode(buf);
result = new String(charBuffer.toString().trim());
} catch (IOException e) {
socket.close();
key.cancel();
reducesessions();
//e.printStackTrace();
}
return result;
}
private void readxml() {
String strport, strmax;
try {
File f = new File("CenterInfo.xml");
if (f.exists()) {
DocumentBuilderFactory factory = DocumentBuilderFactory.
newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document doc = builder.parse(f);
NodeList nl = doc.getElementsByTagName("Center");
for (int i = 0; i < nl.getLength(); i++) {
centerIP = (doc.getElementsByTagName("CenterIP").item(i).
getFirstChild().
getNodeValue()).trim();
strport = (doc.getElementsByTagName("CenterPort").item(i).
getFirstChild().
getNodeValue()).trim();
strmax = (doc.getElementsByTagName("MaxConnection").item(i).
getFirstChild().
getNodeValue()).trim();
CodeType = (doc.getElementsByTagName("CodeType").item(i).
getFirstChild().
getNodeValue()).trim();
super.centerPort = strport;
super.centerIp = centerIP;
try {
if (strport.length() > 0) {
centerPort = Integer.parseInt(strport);
} else {
System.out.println("TerminalPort err");
System.exit( -1);
}
if (strmax.length() > 0) {
MaxConnection = Integer.parseInt(strmax);
} else {
System.out.println("MaxConnection err");
System.exit( -1);
}
} catch (Exception e) {
System.out.println("centerPort and MaxConnection err");
}
}
} else {
System.out.println("no find file:CenterInfo.xml");
System.exit( -1);
}
} catch (Exception e) {
e.printStackTrace();
System.exit( -1);
}
// try {
// this.CenterIp = InetAddress.getLocalHost().getHostAddress();
// }
// catch (UnknownHostException e) {
// e.printStackTrace();
// }
}
}