在 spring 中起 socket serialport webservice 服务

阅读更多

-----------------------------pom.xml-----------------------------------------
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

    anole.server
    webmis
    1.0-SNAPSHOT
    war
    MIS
   
        ${project.build.directory}/endorsed
        UTF-8
        Tomcat70
   

   
       
            org.rxtx
            rxtx
            2.1.7
       

       
            javax
            javaee-web-api
            6.0
            provided
       

       
            junit
            junit
            4.8.2
            test
       


       
            org.apache.cxf
            cxf-bundle
            2.4.1
            runtime
       


       
            org.hibernate
            hibernate-entitymanager
            3.3.2.GA
       

       
            javax.sql
            jdbc-stdext
            2.0
       

       
            javax.transaction
            jta
            1.1
       

       
            org.hibernate
            hibernate-annotations
            3.5.6-Final
       

       
            org.hibernate
            ejb3-persistence
            3.3.2.Beta1
       

       
            javax.persistence      
            persistence-api      
            1.0    
       

       
            org.springframework
            spring-core
            3.0.5.RELEASE
       

       
            org.springframework
            spring-aop
            3.0.5.RELEASE
       

       
            org.springframework
            spring-aspects
            3.0.5.RELEASE
       

       
            org.springframework
            spring-orm
            3.0.5.RELEASE
       

       
            org.springframework
            spring-jms
            3.0.5.RELEASE
       

       
            org.springframework
            spring-jdbc
            3.0.5.RELEASE
       

       
            org.springframework
            spring-instrument
            3.0.5.RELEASE
       

       
            org.springframework
            spring-asm
            3.0.5.RELEASE
       

       
            org.springframework
            spring-context-support
            3.0.5.RELEASE
       

       
            org.springframework
            spring-web
            3.0.5.RELEASE
       

         
            c3p0 
            c3p0 
            0.9.1.2
       

         
            com.oracle 
            ojdbc14 
            10.2.0.3.0
       

         
            org.apache.struts 
            struts2-core 
            2.2.3
       
 
         
            org.apache.struts 
            struts2-convention-plugin
            2.2.3
       
 
 
         
            javax.servlet 
            jstl
            1.2
       
 
         
            taglibs 
            standard
            1.1.2
       
 
       
            aspectj
            aspectjweaver
            1.5.4
       

       
            org.slf4j
            slf4j-api
            1.6.1
       

       
            org.slf4j
            slf4j-jdk14
            1.6.1
       

       
       
            net.sf.ezmorph
            ezmorph
            1.0.6
       

       
            xom
            xom
            1.2.5
       

       
            net.sf.json-lib
            json-lib
            2.4
       


       
            org.apache.struts
            struts2-json-plugin
            2.2.3
       

       
            org.apache.struts
            struts2-spring-plugin
            2.2.3
       

       
            org.apache.commons
            commons-jci-fam
            1.0
       

       
            org.quartz-scheduler
            quartz
            2.0.2
       

       
            org.quartz-scheduler
            quartz-oracle
            2.0.2
       

       
            org.quartz-scheduler
            quartz-weblogic
            2.0.2
       

       
            org.quartz-scheduler
            quartz-jboss
            2.0.2
       

         
            net.sf.ehcache 
            ehcache-core
            2.4.3
       
 
         
            commons-lang 
            commons-lang
            2.6
       
 
         
            commons-beanutils 
            commons-beanutils
            1.8.3
       
 
       
            commons-collections
            commons-collections
            3.2.1
       

       
            log4j
            log4j
            1.2.16
       

   

   
       
           
                org.apache.maven.plugins
                maven-compiler-plugin
                2.3.2
               
                    1.6
                    1.6
                   
                        ${endorsed.dir}
                   

               

           

           
                org.apache.maven.plugins
                maven-war-plugin
                2.1
               
                    false
               

           

           
                org.apache.maven.plugins
                maven-dependency-plugin
                2.1
               
                   
                        validate
                       
                            copy
                       

                       
                            ${endorsed.dir}
                            true
                           
                               
                                    javax
                                    javaee-endorsed-api
                                    6.0
                                    jar
                               

                           

                       

                   

               

           

       

        webmis
   


 

 

---------------------web.xml----------------------配置-----------------------------

 




   
        CXFServlet
        org.apache.cxf.transport.servlet.CXFServlet
        1
   

   
        CXFServlet
        /webservice/*
   

   
        contextConfigLocation
        classpath:/config/spring/applicationContext.xml
   

   
        org.springframework.web.context.ContextLoaderListener
   

   
        struts2
        org.apache.struts2.dispatcher.FilterDispatcher
   

   
        struts2
        *.action
   

   
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
       
            encoding
            UTF-8
       

       
            forceEncoding
            true
       

   

   
        characterEncodingFilter
        *.jsp
   

   
        log4jConfigLocation
        classpath:/config/log4j.properties
   

     
        log4jRefreshInterval 
        30000 
   
  
   
        org.springframework.web.util.Log4jConfigListener
   

   
       
            30
       

   

   
        index.jsp
   

 

 

-------------------spring 配置------------------------

 


       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:lang="http://www.springframework.org/schema/lang"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:jaxws="http://cxf.apache.org/jaxws"

       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
          http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
          http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
          http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-3.0.xsd
          http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
          http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
">
   
   
   
   
   

   
       
   


   
       
   

   
   


-------------------------------------------代码------------

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package anole.server.common.comm.socket;

import anole.server.common.util.CodeConvert;
import anole.server.common.util.NoByteException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Arrays;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;

public class SocketServerHandler extends Thread {

    private InputStream in;
    private OutputStream out;
    private boolean isComplate = true;
    private byte[] readBuffer;
    private int bufferSize = 10240;
    private long timeOut = 4000;
    private boolean isFirst = true;
    private Socket client;
    private int waitTime = 8000;
    private String socketKey;
    private boolean state=true;

    public Socket getClient() {
        return client;
    }

    public void setClient(Socket client) {
        this.client = client;
    }

    public InputStream getIn() {
        return in;
    }

    public void setIn(InputStream in) {
        this.in = in;
    }

    public OutputStream getOut() {
        return out;
    }

    public void setOut(OutputStream out) {
        this.out = out;
    }
    public void setWaitTime(int waitTime) {
        this.waitTime = waitTime;
    }
    public SocketServerHandler(Socket client) throws IOException {
        this.client = client;
        in = this.client.getInputStream();
        out = this.client.getOutputStream();
    }

    @SuppressWarnings("unchecked")
    public void run() {
        try {
            long curr = new Date().getTime();
            while (state) {
                int numBytes = 0;
                byte[] bs = new byte[bufferSize];
                while (getIn().available() > 0) {
                    //将数据读入readBuffer中。 
                    numBytes = getIn().read(bs);
                }
                if (isFirst) {
                    isFirst = false;
                    socketKey=CodeConvert.ByteToString(Arrays.copyOf(bs, numBytes));
                    System.out.println("注册数据" +socketKey);
                    SocketServerManagement.clientSocket.put(socketKey, (SocketServerHandler)Thread.currentThread());
                } else {
                    System.out.println("接收数据" + CodeConvert.ByteToString(bs));
                    setReadBuffer(Arrays.copyOf(bs, numBytes));
                }
                if (numBytes > 0) {
                    curr=new Date().getTime();
                } else {
                    if (new Date().getTime()-curr > waitTime) {
                        getIn().close();
                        getOut().close();
                        getClient().close();
                        SocketServerManagement.clientSocket.remove(socketKey);
                        break;
                    }
                }
                getOut().write(Arrays.copyOf(bs, numBytes));
                getOut().flush();
            }
        } catch (IOException e) {
            System.out.println(e);
            Logger.getLogger(SocketServerHandler.class.getName()).log(Level.SEVERE, null, e);
        }
    }

    public synchronized void setReadBuffer(byte[] readBuffer) {
        isComplate = false;
        while (isComplate) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        byte[] temp = readBuffer;
        if (this.readBuffer != null) {
            if (temp != null) {
                int rLen = this.readBuffer.length;
                int tLen = temp.length;
                byte[] ins = new byte[rLen + tLen];
                System.arraycopy(this.readBuffer, 0, ins, 0, rLen);
                System.arraycopy(temp, 0, ins, rLen, tLen);
            }
        } else {
            this.readBuffer = temp;
        }
        isComplate = true;
        this.notifyAll();
    }

    public synchronized byte[] getReadBuffer() {
        while (!isComplate) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        byte[] temp = this.readBuffer;
        this.readBuffer = null;
        this.notifyAll();
        return temp;
    }

    public void setTimeOut(long timeOut) {
        this.timeOut = timeOut;
    }

    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    public int send(byte[] bs) {
        int flag = 0;
        try {
            getOut().write(bs);
            getOut().flush();
        } catch (IOException e) {
            flag = 2;
        }
        return flag;
    }

    public byte[] recevie(int dataLength, long timeOut) {
        this.timeOut = timeOut;
        byte[] bs = null;
        byte[] temp = null;
        int cLen = 0;
        int tLen = 0;
        int lLen = 0;
        long curr = new Date().getTime();
        while ((bs == null || bs.length < dataLength) && new Date().getTime() - curr < this.timeOut) {
            try {
                //获取缓冲区数据
                temp = null;//临时数据清空
                temp = getReadBuffer();
                tLen = 0;
                if (temp != null) {
                    System.out.println("临时数据:" + CodeConvert.ByteToString(temp));
                    tLen = temp.length;
                }
                //计算要返回数据长度
                if (bs != null) {
                    cLen = bs.length;
                }
                System.out.println("当前数据长度:" + cLen);
                //若 当前要返回数据长度 加上 临时数据长度 大于 要求的数据长度
                if ((cLen + tLen) > dataLength) {
                    System.out.println("长度超出" + (cLen + tLen));
                    //计算需要拷贝的数据长度
                    lLen = dataLength - cLen;
                    byte[] ins = new byte[cLen + lLen];
                    System.arraycopy(bs, 0, ins, 0, cLen);
                    System.arraycopy(temp, 0, ins, cLen, lLen);
                    bs = ins;
                    break;
                } //将临时数据追加到要返回的数据之后
                else if (temp != null && bs != null) {
                    //将临时数组添加到当前数组之后
                    System.out.println("附加数据");
                    byte[] in = new byte[cLen + tLen];
                    System.arraycopy(bs, 0, in, 0, cLen);
                    System.arraycopy(temp, 0, in, cLen, tLen);
                    bs = in;
                } else if (temp != null && bs == null) {
                    System.out.println("初始化数组");
                    bs = temp;
                }
                //若 数据长度不够 则 线程睡眠1000ms
                if (bs != null) {
                    cLen = bs.length;
                }
                if (cLen < dataLength) {
                    System.out.println("线程睡眠1000ms");
                    Thread.sleep(1000);
                }

            } catch (InterruptedException ex) {
                Logger.getLogger(SocketServerHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        int aLen = bs.length;
        bs = Arrays.copyOf(bs, aLen);
        System.out.println("当前返回数据:" + CodeConvert.ByteToString(bs));
        return bs;
    }

    public byte[] recevie(byte endFlag, long timeOut) {
        this.timeOut = timeOut;
        byte[] bs = null;
        byte[] temp = null;
        int cLen = 0;
        int tLen = 0;
        int lLen = 0;
        int iIndex = -1;
        long curr = new Date().getTime();
        while (iIndex < 0 && new Date().getTime() - curr < this.timeOut) {
            try {
                //获取缓冲区数据
                temp = null;
                tLen = 0;
                temp = getReadBuffer();
                if (temp != null) {
                    System.out.println("临时数据:" + CodeConvert.ByteToString(temp));
                    tLen = temp.length;
                }

                //计算要返回数据长度
                if (bs != null) {
                    cLen = bs.length;
                }

                System.out.println("临时数据长度:" + tLen);

                for (int i = 0; i < tLen; i++) {
                    if (temp[i] == endFlag) {
                        iIndex = i + 1;
                    }
                }
                System.out.println("位置:" + iIndex);

                lLen = tLen + cLen;

                //若 临时数据中未发现结束符
                if (iIndex < 0) {
                    //扩容 追加到要返回的数据之后
                    byte[] ins = new byte[lLen];
                    if (temp != null && bs != null) {
                        System.arraycopy(bs, 0, ins, 0, cLen);
                        System.arraycopy(temp, 0, ins, cLen, tLen);
                        bs = ins;

                    } else if (temp != null && bs == null) {
                        bs = temp;
                    }
                    Thread.sleep(1000);
                } else {
                    if (temp != null && bs != null) {//非第一个包中就包含了结束符号
                        //扩容 追加到要返回的数据之后
                        byte[] in = new byte[lLen];
                        System.arraycopy(bs, 0, in, 0, cLen);
                        System.arraycopy(temp, 0, in, cLen, iIndex);
                        bs = in;
                        break;
                    } else if (temp != null && bs == null) {//第一个包中就包含了结束符号
                        bs = Arrays.copyOf(temp, iIndex);
                        break;
                    }
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(SocketServerHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        int aLen = new String(bs).trim().length();
        bs = Arrays.copyOf(bs, aLen);
        System.out.println("返回的数据:" + CodeConvert.ByteToString(bs));
        return bs;
    }
    public int send(String comCode, String splitFlag) {
        int flag = 0;
        byte[] bs = null;
        try {
            bs = CodeConvert.StringToByte(comCode, splitFlag);
        } catch (NoByteException ne) {
            flag = 1;
        }
        flag = send(bs);
        return flag;
    }

    public int send(String comCode) {
        int flag = 0;
        byte[] bs = null;
        try {
            bs = CodeConvert.StringToByte(comCode);
        } catch (NoByteException ne) {
            flag = 1;
        }
        flag = send(bs);
        return flag;
    }

    public int send(char[] comCode) {
        int flag = 0;
        byte[] bs = null;
        bs = CodeConvert.CharsToBytes(comCode);
        flag = send(bs);
        return flag;
    }

    public byte[] recevie(String endFlag, long timeout) {
        byte[] bs = null;
        byte ef = 0;
        try {
            ef = CodeConvert.StringToByte(endFlag)[0];
        } catch (NoByteException ne) {
            int flag = 1;
        }
        this.recevie(ef, timeout);
        return bs;
    }

    public byte[] recevie() {
        return readBuffer;
    }

    public void setState(boolean state) {
        this.state = state;
    }
}
package anole.server.common.comm.socket;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ServerSocketFactory;

public class SocketServerManagement extends Thread {

    private int socketPort = 4900;
    private int waitTime = 8000;
    private int maxConnect = 100;
    protected static Map clientSocket = new HashMap();
    private boolean state = true;

    @Override
    public void run() {
        ServerSocketFactory serverSocketFactory = ServerSocketFactory.getDefault();
        System.out.println("------------------获取连接工厂------------------");
        try {
            ServerSocket server = serverSocketFactory.createServerSocket(socketPort);
            System.out.println("------------------创建服务端口------------------");
            Socket request = null;
            System.out.println("------------------ ServerSocket已经启动 ------------------");
            while (state) {
                request = server.accept();
                System.out.println("------------------ 客户请求成功 ------------------");
                SocketServerHandler ssh = new SocketServerHandler(request);
                ssh.setWaitTime(waitTime);
                ssh.start();
            }
        } catch (IOException ex) {
            Logger.getLogger(SocketServerManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public SocketServerHandler getSocketServerHandler(String key) {
        return clientSocket.get(key);
    }

    public void setSocketServerHandler(String key, SocketServerHandler socketServerHandler) {
        clientSocket.put(key, socketServerHandler);
    }

    public void removeSocketServerHandler(String key) {
        SocketServerHandler t = clientSocket.get(key);
        try {
            t.getIn().close();
            t.getOut().close();
            t.getClient().close();
            t.setState(state);//设置结束标识
            t.interrupt();//打断线程
            clientSocket.remove(key);
        } catch (IOException ex) {
            Logger.getLogger(SocketServerManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    public int close() {
        state = false;//结束线程标识
        Iterator iter = clientSocket.keySet().iterator();
        String key;
        System.out.println("---------------需要关闭的线程个数:" + clientSocket.size());
        while (iter.hasNext()) {
            key = iter.next();
            removeSocketServerHandler(key);
        }
        System.out.println("--------------关闭主线程");
        this.interrupt();
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Logger.getLogger(SocketServerManagement.class.getName()).log(Level.SEVERE, null, ex);
        }
        System.out.println("--------------关闭主线程结束");
        return 0;
    }

    public int send(String hexString, String clientId) {
        SocketServerHandler ssh = getSocketServerHandler(clientId);
        return ssh.send(hexString);
    }

    public byte[] receive(String clientId) {
        SocketServerHandler ssh = getSocketServerHandler(clientId);
        return ssh.recevie();
    }

    public byte[] receive(String clientId, String endFlag, int timeOut) {
        SocketServerHandler ssh = getSocketServerHandler(clientId);
        return ssh.recevie(endFlag, timeOut);
    }

    public byte[] receive(String clientId, int dataLength, int timeOut) {
        SocketServerHandler ssh = getSocketServerHandler(clientId);
        return ssh.recevie(dataLength, timeOut);
    }

    public int getSocketPort() {
        return socketPort;
    }

    public void setSocketPort(int socketPort) {
        this.socketPort = socketPort;
    }

    public int getWaitTime() {
        return waitTime;
    }

    public void setWaitTime(int waitTime) {
        this.waitTime = waitTime;
    }
}
package anole.server.service.comm;

import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService
public interface SocketService {

    public int open(@WebParam(name = "socketPort") int socketPort);

    public int close();

    public int send(@WebParam(name = "hexString") String hexString, @WebParam(name = "clientId") String clientId);

    public byte[] receive(@WebParam(name = "clientId") String clientId);

    @WebMethod(operationName = "receiveByEndFlag")
    public byte[] receive(@WebParam(name = "clientId") String clientId, @WebParam(name = "endFlag") String endFlag, @WebParam(name = "timeOut") int timeOut);

    @WebMethod(operationName = "receiveByDataLength")
    public byte[] receive(@WebParam(name = "clientId") String clientId, @WebParam(name = "dataLength") int dataLength, @WebParam(name = "timeOut") int timeOut);
}
package anole.server.service.comm.impl;

import anole.server.common.comm.socket.SocketServerManagement;
import anole.server.service.comm.SocketService;
import javax.jws.WebService;

@WebService(endpointInterface = "anole.server.service.comm.SocketService", serviceName = "SocketService")
public class SocketServiceImpl implements SocketService {

    private SocketServerManagement socketServerManagement;

    @Override
    public int open(int socketPort) {
        socketServerManagement.setSocketPort(socketPort);
        try {
           socketServerManagement.start();
            return 0;
        } catch (Exception e) {
            return 1;
        }
    }

    @Override
    public int close() {
        return socketServerManagement.close();
    }

    @Override
    public int send(String hexString, String clientId) {
        return socketServerManagement.send(hexString, clientId);
    }

    @Override
    public byte[] receive(String clientId) {
        return socketServerManagement.receive(clientId);
    }

    @Override
    public byte[] receive(String clientId, String endFlag, int timeOut) {
        return socketServerManagement.receive(clientId, endFlag, timeOut);
    }

    @Override
    public byte[] receive(String clientId, int dataLength, int timeOut) {
        return socketServerManagement.receive(clientId, dataLength, timeOut);
    }

    public SocketServerManagement getSocketServerManagement() {
        return socketServerManagement;
    }

    public void setSocketServerManagement(SocketServerManagement socketServerManagement) {
        this.socketServerManagement = socketServerManagement;
    }
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package anole.server.common.comm.serial;

import anole.server.common.util.CodeConvert;
import anole.server.common.util.NoByteException;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Administrator
 */
public class SerialServerHandler implements SerialPortEventListener {

    private SerialPort serialPort;
    private long timeOut = 4000;
    private String portName;
    private OutputStream os;
    private InputStream is;
    private int rate = 9600;
    private int dataBit = SerialPort.DATABITS_8;
    private int stopBit = SerialPort.STOPBITS_1;
    private int parity = SerialPort.PARITY_NONE;
    private boolean isComplate = true;
    private byte[] readBuffer;
    private int bufferSize = 10240;

    public synchronized void setReadBuffer(byte[] readBuffer) {
        isComplate = false;
        while (isComplate) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        byte[] temp = readBuffer;
        if (this.readBuffer != null) {
            if (temp != null) {
                int rLen = this.readBuffer.length;
                int tLen = temp.length;
                byte[] in = new byte[rLen + tLen];
                System.arraycopy(this.readBuffer, 0, in, 0, rLen);
                System.arraycopy(temp, 0, in, rLen, tLen);
            }
        } else {
            this.readBuffer = temp;
        }
        isComplate = true;
        this.notifyAll();
    }

    public synchronized byte[] getReadBuffer() {
        while (!isComplate) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        byte[] temp = this.readBuffer;
        this.readBuffer = null;
        this.notifyAll();
        return temp;
    }

    public void setTimeOut(long timeOut) {
        this.timeOut = timeOut;
    }

    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    public int send(byte[] bs) {
        int flag = 0;
        try {
            os.write(bs);
            os.flush();
        } catch (IOException e) {
            flag = 2;
        }
        return flag;
    }

    public byte[] recevie(int dataLength, long timeOut) {
        this.timeOut = timeOut;
        byte[] bs = null;
        byte[] temp = null;
        int cLen = 0;
        int tLen = 0;
        int lLen = 0;
        long curr = new Date().getTime();
        while ((bs == null || bs.length < dataLength) && new Date().getTime() - curr < this.timeOut) {
            try {
                //获取缓冲区数据
                temp = null;//临时数据清空
                temp = getReadBuffer();
                tLen = 0;
                if (temp != null) {
                    System.out.println("临时数据:" + CodeConvert.ByteToString(temp));
                    tLen = temp.length;
                }
                //计算要返回数据长度
                if (bs != null) {
                    cLen = bs.length;
                }
                System.out.println("当前数据长度:" + cLen);
                //若 当前要返回数据长度 加上 临时数据长度 大于 要求的数据长度
                if ((cLen + tLen) > dataLength) {
                    System.out.println("长度超出" + (cLen + tLen));
                    //计算需要拷贝的数据长度
                    lLen = dataLength - cLen;
                    byte[] in = new byte[cLen + lLen];
                    System.arraycopy(bs, 0, in, 0, cLen);
                    System.arraycopy(temp, 0, in, cLen, lLen);
                    bs = in;
                    break;
                } //将临时数据追加到要返回的数据之后
                else if (temp != null && bs != null) {
                    //将临时数组添加到当前数组之后
                    System.out.println("附加数据");
                    byte[] in = new byte[cLen + tLen];
                    System.arraycopy(bs, 0, in, 0, cLen);
                    System.arraycopy(temp, 0, in, cLen, tLen);
                    bs = in;
                } else if (temp != null && bs == null) {
                    System.out.println("初始化数组");
                    bs = temp;
                }
                //若 数据长度不够 则 线程睡眠1000ms
                if (bs != null) {
                    cLen = bs.length;
                }
                if (cLen < dataLength) {
                    System.out.println("线程睡眠1000ms");
                    Thread.sleep(1000);
                }

            } catch (InterruptedException ex) {
                Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        int aLen = bs.length;
        bs = Arrays.copyOf(bs, aLen);
        System.out.println("当前返回数据:" + CodeConvert.ByteToString(bs));
        return bs;
    }

    public byte[] recevie(byte endFlag, long timeOut) {
        this.timeOut = timeOut;
        byte[] bs = null;
        byte[] temp = null;
        int cLen = 0;
        int tLen = 0;
        int lLen = 0;
        int iIndex = -1;
        long curr = new Date().getTime();
        while (iIndex < 0 && new Date().getTime() - curr < this.timeOut) {
            try {
                //获取缓冲区数据
                temp = null;
                tLen = 0;
                temp = getReadBuffer();
                if (temp != null) {
                    System.out.println("临时数据:" + CodeConvert.ByteToString(temp));
                    tLen = temp.length;
                }

                //计算要返回数据长度
                if (bs != null) {
                    cLen = bs.length;
                }

                System.out.println("临时数据长度:" + tLen);

                for (int i = 0; i < tLen; i++) {
                    if (temp[i] == endFlag) {
                        iIndex = i + 1;
                    }
                }
                System.out.println("位置:" + iIndex);

                lLen = tLen + cLen;

                //若 临时数据中未发现结束符
                if (iIndex < 0) {
                    //扩容 追加到要返回的数据之后
                    byte[] in = new byte[lLen];
                    if (temp != null && bs != null) {
                        System.arraycopy(bs, 0, in, 0, cLen);
                        System.arraycopy(temp, 0, in, cLen, tLen);
                        bs = in;

                    } else if (temp != null && bs == null) {
                        bs = temp;
                    }
                    Thread.sleep(1000);
                } else {
                    if (temp != null && bs != null) {//非第一个包中就包含了结束符号
                        //扩容 追加到要返回的数据之后
                        byte[] in = new byte[lLen];
                        System.arraycopy(bs, 0, in, 0, cLen);
                        System.arraycopy(temp, 0, in, cLen, iIndex);
                        bs = in;
                        break;
                    } else if (temp != null && bs == null) {//第一个包中就包含了结束符号
                        bs = Arrays.copyOf(temp, iIndex);
                        break;
                    }
                }
            } catch (InterruptedException ex) {
                Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        int aLen = new String(bs).trim().length();
        bs = Arrays.copyOf(bs, aLen);
        System.out.println("返回的数据:" + CodeConvert.ByteToString(bs));
        return bs;
    }

    public byte[] recevie() {
        return readBuffer;
    }

    ;

    @Override
    public void serialEvent(SerialPortEvent event) {
        switch (event.getEventType()) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:
                try {
                    int numBytes = 0;
                    byte[] bs = new byte[bufferSize];
                    while (is.available() > 0) {
                        //将数据读入readBuffer中。 
                        numBytes = is.read(bs);
                    }
                    setReadBuffer(Arrays.copyOf(bs, numBytes));
                } catch (IOException e) {
                    Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, e);
                }
                break;
        }
    }

    public int open() {
        int flag = 0;
        CommPortIdentifier portId = null;
        System.out.println("-------当前打开串口:" + portName);
        try {
            portId = CommPortIdentifier.getPortIdentifier(portName);
        } catch (NoSuchPortException e) {
            flag = 3;//未找到端口
            Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, e);
        }
        try {
            serialPort = (SerialPort) portId.open(SerialServerListener.class.getSimpleName(), 2000);
        } catch (PortInUseException e) {
            flag = 4;//端口被占用
            Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, e);
        }
        try {
            serialPort.setSerialPortParams(rate, dataBit, stopBit, parity);
            System.out.println("开启端口:portName-" + portName + ":::rate-" + rate + ":::dataBit-" + dataBit + ":::stopBit-" + stopBit + ":::parity-" + parity);
            //serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
        } catch (UnsupportedCommOperationException e) {
            flag = 2;//端口设置错误
            Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, e);
        }
        try {
            is = serialPort.getInputStream();
            os = serialPort.getOutputStream();
        } catch (IOException e) {
            flag = 5;//IO开启异常
            Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, e);
        }
        try {
            serialPort.addEventListener(this); // 给当前串口天加一个监听器
        } catch (TooManyListenersException e) {
            flag = 6;//监听器添加异常
            Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, e);
        }
        serialPort.notifyOnDataAvailable(true); // 当有数据时通知 
        return flag;
    }

    public int send(String comCode, String splitFlag) {
        int flag = 0;
        byte[] bs = null;
        try {
            bs = CodeConvert.StringToByte(comCode, splitFlag);
        } catch (NoByteException ne) {
            flag = 1;
        }
        flag = send(bs);
        return flag;
    }

    public int send(String comCode) {
        int flag = 0;
        byte[] bs = null;
        try {
            bs = CodeConvert.StringToByte(comCode);
        } catch (NoByteException ne) {
            flag = 1;
        }
        flag = send(bs);
        return flag;
    }

    public int send(char[] comCode) {
        int flag = 0;
        byte[] bs = null;
        bs = CodeConvert.CharsToBytes(comCode);
        flag = send(bs);
        return flag;
    }

    public byte[] recevie(String endFlag, long timeout) {
        byte[] bs = null;
        byte ef = 0;
        try {
            ef = CodeConvert.StringToByte(endFlag)[0];
        } catch (NoByteException ne) {
            int flag = 1;
        }
        this.recevie(ef, timeout);
        return bs;
    }

    public int close() {
        int flag = 0;
        try {
            if (is != null) {
                is.close();
            }
            if (os != null) {
                os.close();
            }
            if (serialPort != null) {
                serialPort.close();
            }
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ex) {
                Logger.getLogger(SerialServerHandler.class.getName()).log(Level.SEVERE, null, ex);
            }
        } catch (IOException e) {
            flag = 1;
        }
        return flag;
    }

    public List getListPortName() {
        List listPortName = new ArrayList();
        CommPortIdentifier portId;
        @SuppressWarnings("unchecked")
        Enumeration en = CommPortIdentifier.getPortIdentifiers();
        while (en.hasMoreElements()) {
            portId = en.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
                listPortName.add(portId.getName());
            }
        }
        return listPortName;
    }

    public void setRate(int rate) {
        this.rate = rate;
    }

    public void setDataBit(int dataBit) {
        this.dataBit = dataBit;
    }

    public void setStopBit(int stopBit) {
        this.stopBit = stopBit;
    }

    public void setParity(int parity) {
        this.parity = parity;
    }

    public void setPortName(String portName) {
        this.portName = portName;
    }
}
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package anole.server.common.comm.serial;

import gnu.io.SerialPort;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Administrator
 */
public class SerialServerManagement extends Thread {

    private Map portInstance = new HashMap();
    private SerialPort serialPort;
    private long timeOut = 4000;
    private String portName;
    private int rate = 9600;
    private int dataBit = SerialPort.DATABITS_8;
    private int stopBit = SerialPort.STOPBITS_1;
    private int parity = SerialPort.PARITY_NONE;
    private boolean isComplate = true;
    private byte[] readBuffer;
    private int bufferSize = 10240;
    @Override
    public void run() {
        int i = this.open();
    }

    public List listPortName() {
        SerialServerHandler serialServerHandler = new SerialServerHandler();
        return serialServerHandler.getListPortName();
    }
   
    public int open() {
        int flag = 0;
        SerialServerHandler serialServerHandler = new SerialServerHandler();
        serialServerHandler.setBufferSize(bufferSize);
        serialServerHandler.setDataBit(dataBit);
        serialServerHandler.setParity(parity);
        serialServerHandler.setPortName(portName);
        serialServerHandler.setRate(rate);
        serialServerHandler.setStopBit(stopBit);
        serialServerHandler.setTimeOut(timeOut);
        flag = serialServerHandler.open();
        getPortInstance().put(portName, serialServerHandler);
        return flag;
    }
    public int close(String serialPort){
        SerialServerHandler ssh=getPortInstance().get(serialPort);
        return ssh.close();
    }
    public int close() {
        int flag = 0;
        Iterator iter =getPortInstance().keySet().iterator();
        String key;
        SerialServerHandler ssh;
        while(iter.hasNext()){
            key=iter.next();
            ssh=getPortInstance().get(key);
            ssh.close();
        }
        return flag;
    }
    public int send(String hexString, String serialPort){
        SerialServerHandler ssh=getPortInstance().get(serialPort);
        return ssh.send(hexString);
    }
    public byte[] receive(String serialPort){
        SerialServerHandler ssh=getPortInstance().get(serialPort);
        return ssh.recevie();
    }

    public byte[] receive(String serialPort, String endFlag, int timeOut) {
        SerialServerHandler ssh=getPortInstance().get(serialPort);
        return ssh.recevie(endFlag, timeOut);
    }

    public byte[] receive(String serialPort, int dataLength, int timeOut) {
        SerialServerHandler ssh=getPortInstance().get(serialPort);
        return ssh.recevie(dataLength, timeOut);
    }
    public void setSerialPort(SerialPort serialPort) {
        this.serialPort = serialPort;
    }

    public void setTimeOut(long timeOut) {
        this.timeOut = timeOut;
    }

    public void setPortName(String portName) {
        this.portName = portName;
    }

    public void setRate(int rate) {
        this.rate = rate;
    }

    public void setDataBit(int dataBit) {
        this.dataBit = dataBit;
    }

    public void setStopBit(int stopBit) {
        this.stopBit = stopBit;
    }

    public void setParity(int parity) {
        this.parity = parity;
    }

    public void setIsComplate(boolean isComplate) {
        this.isComplate = isComplate;
    }

    public void setReadBuffer(byte[] readBuffer) {
        this.readBuffer = readBuffer;
    }

    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    public Map getPortInstance() {
        return portInstance;
    }

    public void setPortInstance(Map portInstance) {
        this.portInstance = portInstance;
    }
}
package anole.server.service.comm.impl;

import anole.server.common.comm.serial.SerialServerManagement;
import anole.server.service.comm.SerialService;
import java.util.List;
import javax.jws.WebService;

@WebService(endpointInterface = "anole.server.service.comm.SerialService", serviceName = "SerialService")
public class SerialServiceImpl implements SerialService {
    private SerialServerManagement serialServerManagement;
    @Override
    public int open(String serialPort) {
        serialServerManagement.setPortName(serialPort);
        return serialServerManagement.open();
    }
   
    @Override
    public List listPortName(){
        return serialServerManagement.listPortName();
    }
    @Override
    public int close(String serialPort) {
       return serialServerManagement.close(serialPort);
    }

    @Override
    public int send(String hexString, String serialPort) {
        return serialServerManagement.send(hexString, serialPort);
    }

    @Override
    public byte[] receive(String serialPort) {
        return serialServerManagement.receive(serialPort);
    }

    @Override
    public byte[] receive(String serialPort, String endFlag, int timeOut) {
        return serialServerManagement.receive(serialPort, endFlag, timeOut);
    }

    @Override
    public byte[] receive(String serialPort, int dataLength, int timeOut) {
       return serialServerManagement.receive(serialPort, dataLength, timeOut);
    }

    public SerialServerManagement getSerialServerManagement() {
        return serialServerManagement;
    }

    public void setSerialServerManagement(SerialServerManagement serialServerManagement) {
        this.serialServerManagement = serialServerManagement;
    }
}
package anole.server.service.comm;

import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService
public interface SerialService {

    public List listPortName();

    public int open(@WebParam(name = "serialPort") String serialPort);

    public int close(@WebParam(name = "serialPort") String serialPort);

    public int send(@WebParam(name = "hexString") String hexString, @WebParam(name = "serialPort") String serialPort);

    public byte[] receive(@WebParam(name = "serialPort") String serialPort);

    @WebMethod(operationName = "receiveByEndFlag")
    public byte[] receive(@WebParam(name = "serialPort") String serialPort, @WebParam(name = "endFlag") String endFlag, @WebParam(name = "timeOut") int timeOut);

    @WebMethod(operationName = "receiveByDataLength")
    public byte[] receive(@WebParam(name = "serialPort") String serialPort, @WebParam(name = "dataLength") int dataLength, @WebParam(name = "timeOut") int timeOut);
}

你可能感兴趣的:(socket,spring,webservice,串口)