日期:2014-05-20 浏览次数:20839 次
<iabi> <cmd id= "3000 " sessionid= "1412412341 "> <confid> 88888888 </confid> </cmd> </iabi>
public class SocketServer extends Thread { private Logger log= Logger.getLogger(SocketServer.class.getName()); private ServerSocket serverSocket; private int listenPort =8188; public SocketServer(int listenPort) { this.listenPort = listenPort; } public static Map socketMap=new HashMap();//保存socket的HashMap public static Map resultMap=new HashMap();//保存发出通信的的返回结果Map private Socket socket; private boolean isLoop= false; public void run(){ isLoop=true; try { serverSocket= new ServerSocket(listenPort); log.info("Starting listen......"); String ccsIp=""; CcsInfo ccsInfo=null; while(isLoop){ socket = serverSocket.accept(); log.info("Listening->RemoteSocketAddress:"+socket.getRemoteSocketAddress()+" InetAddress:"+socket.getInetAddress()); ccsIp=socket.getRemoteSocketAddress().toString().trim(); ccsIp=ccsIp.substring(1,ccsIp.indexOf(":")); log.info("RemoteSocketIp:"+ccsIp); socketMap.put(ccsIp,socket); log.info("Having listen the IP:" +ccsIp+" The ccsID:"+ccsInfo.getCcsId()); new SocketServerThread(socket).start(); } } catch (Exception e) { isLoop = false; log.error(" "+e); } } }
public class SocketServerThread extends Thread { private Logger log= Logger.getLogger(SocketServerThread.class.getName()); private Socket socket; private int result; private boolean isLoop; ByteArrayOutputStream buf = new ByteArrayOutputStream(); public SocketServerThread(Socket s){ this.socket = s; } public void run(){ isLoop=true; result=0; InputStream in=null; try { in =new BufferedInputStream(socket.getInputStream()); } catch (IOException e){ log.error("The CCS "+socket.getRemoteSocketAddress()+" is unusual:"+e); } int readLen=1024; int count=0; byte[] readBuf=new byte[readLen]; while(true&&isLoop){ count=0; try{ do{ count=in.read(readBuf); if(count==-1){ isLoop=false; throw new IOException("The receive data length is not right"); } buf.write(readBuf,0,count); }while (count==readLen); log.info("Receive:"+new String(buf.toByteArray())); }catch(IOException ex){ log.error("The CCS "+socket.getRemoteSocketAddress()+" correspondence is unusual:"+ex); } //收到的结果是一个xml体,然后解析出sessionid和通信的结果result SocketServer.resultMap.put(sessionid,result);//保存返回结果 } } }