⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 commportserver.java

📁 This package making a GPRS connection using Tini (from Dallas Semiconductors). After connection the
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
			    if( commToSocketConnector == null)
			    {
				    commToSocketConnector =
					    new StreamConnector( cpis, streamSocketOutputStream)
					    {
						    public void dataWritten( int bytesWritten)
						    {
							    dataAvailableNotification( bytesWritten);
						    }
					    };
				    commToSocketConnector.start();
			    }
    			
			    break;
		    case GET_OUTPUT_STREAM:
			    if( socketToCommConnector == null)
			    {
				    socketToCommConnector =
					    new StreamConnector( streamSocketInputStream, cpos)
					    {
						    public void dataWritten( int bytesWritten)
						    {
							    dataWrittenNotification( bytesWritten);
						    }
					    };
				    socketToCommConnector.start();
			    }

			    break;
		    case CLOSE:
			    synchronized( this)
			    {
				    // Step down to RUNNING state only if we are still in the
				    // CONNECTED state.  This check is needed to ensure that
				    // we don't step on someone else's request to go to the
				    // STOPPING or STOPPED state.
				    if( state == CONNECTED)
				    {
					    setState( RUNNING);
				    }
			    }
			    break;
		    case ENABLE_RECEIVE_THRESHOLD:
		        p0 = cis.readInt();
			    cp.enableReceiveThreshold( p0);
			    break;
		    case DISABLE_RECEIVE_THRESHOLD:
			    cp.disableReceiveThreshold();
			    break;
		    case IS_RECEIVE_THRESHOLD_ENABLED:
			    retVal = cp.isReceiveThresholdEnabled() ? TRUE : FALSE;
			    break;
		    case GET_RECEIVE_THRESHOLD:
			    retVal = cp.getReceiveThreshold();
			    break;
		    case ENABLE_RECEIVE_TIMEOUT:
		        p0 = cis.readInt();
			    cp.enableReceiveTimeout( p0);
			    break;
		    case DISABLE_RECEIVE_TIMEOUT:
			    cp.disableReceiveTimeout();
			    break;
		    case IS_RECEIVE_TIMEOUT_ENABLED:
			    retVal = cp.isReceiveThresholdEnabled() ? TRUE : FALSE;
			    break;
		    case GET_RECEIVE_TIMEOUT:
			    retVal = cp.getReceiveTimeout();
			    break;
		    case ENABLE_RECEIVE_FRAMING:
		        p0 = cis.readInt();
			    cp.enableReceiveFraming( p0);
			    break;
		    case DISABLE_RECEIVE_FRAMING:
			    cp.disableReceiveFraming();
			    break;
		    case IS_RECEIVE_FRAMING_ENABLED:
			    retVal = cp.isReceiveFramingEnabled() ? TRUE : FALSE;
			    break;
		    case GET_RECEIVE_FRAMING_BYTE:
			    retVal = cp.getReceiveFramingByte();
			    break;
		    case SET_INPUT_BUFFER_SIZE:
		        p0 = cis.readInt();
			    cp.setInputBufferSize( p0);
			    break;
		    case GET_INPUT_BUFFER_SIZE:
			    retVal = cp.getInputBufferSize();
			    break;
		    case SET_OUTPUT_BUFFER_SIZE:
		        p0 = cis.readInt();
			    cp.setOutputBufferSize( p0);
			    break;
		    case GET_OUTPUT_BUFFER_SIZE:
			    retVal = cp.getOutputBufferSize();
			    break;
		}

		cos.writeInt( OK);
	    cos.writeInt( retVal);
	}

	// This method exists soley for subclasses that need to know when
	// data has been read form the comm port and written to the socket
	// so they can, for example, inform the other end that data is available.
	protected void dataAvailableNotification( int bytesAvailable) {}

	// This method exists soley for subclasses that need to know when
	// data has been read from the socket and written to the comm port
	// so they can, for example, inform the other end that data was written.
	protected void dataWrittenNotification( int bytesWritten) {}

    /* Accept a socket connection on the server socket and create its
     * DataInput/OutputStreams so we have access to those nifty readInt,
     * writeInt methods
     */
	protected Socket accept( ServerSocket ss, int expectedConnId, Object[] streams) throws IOException
	{
		long timeout = System.currentTimeMillis() + 5000;
		while( System.currentTimeMillis() < timeout)
		{
			Socket s = null;

			s = ss.accept();

            DataInputStream dis = new DataInputStream(s.getInputStream());
            DataOutputStream dos = new DataOutputStream(s.getOutputStream());
			if( DEBUG) System.out.println( "InStream=" + dis.readLine() + " OutStream=" + dos.toString() );

            int connId = dis.readInt();
			if( true) // connId == expectedConnId)
			{
                streams[0] = dis;
                streams[1] = dos;
				return s;
			}
            
            if( DEBUG) System.out.println( "Expected connId " + expectedConnId + ", but got " + connId);

			closeSocket( s);
		}
		throw new InterruptedIOException( "Connection timed out.");
	}

	protected void closeSocket( Socket s)
	{
		// Close socket if non-null
		if( s != null)
		{
			try 
			{ 
			    s.close(); 
			}
			catch( IOException ioe) { /* Ignore */ }
		}
	}

    /* Make sure we kill off all the threads runnin around here
     */
	protected void close()
	{
        //tell the StreamConnection threads to stop reading...
        if (socketToCommConnector!=null)
        {
            socketToCommConnector.interrupt();
            socketToCommConnector = null;
        }
        if (commToSocketConnector!=null)
        {
            commToSocketConnector.interrupt();
            commToSocketConnector = null;
        }
        
		closeSocket(controlSocket);
		closeSocket(streamSocket);
		closeSocket(eventSocket);
		controlSocket = null;
		streamSocket = null;
		eventSocket = null;
		
        if( DEBUG) System.out.println( "Sockets closed.");
        
        

		// Close comm port if non-null
        /*
            if we ever want to close the serial port when the user requests it,
            uncomment the following code...
        if( cp != null)
        {
            if( DEBUG) System.out.println( "Closing comm port");
	        cp.close();
	        cp = null;
            if( DEBUG) System.out.println( "Comm port closed");
        }*/
        
        //now might be a nice time to sit back, kick up our heels,
        //and go get the trash
        System.gc();
	}

	public static CommPortServer createPortServer( String commPortName)
	throws NoSuchPortException, UnsupportedCommOperationException, PortInUseException
	{
		return createPortServer(commPortName, DEFAULT_TCP_PORT);
	}

	public static CommPortServer createPortServer(String commPortName, int tcpPort)
	throws NoSuchPortException, UnsupportedCommOperationException, PortInUseException
	{
		CommPortIdentifier cpi = CommPortIdentifier.getPortIdentifier( commPortName);

		if (cpi.getPortType() == CommPortIdentifier.PORT_SERIAL)
		{
            try
            {		    
	            cp = cpi.open( "tcpcomm", 0);

                cpos = cp.getOutputStream();
                cpis = cp.getInputStream();
                        
	            try 
	            { 
		            cp.enableReceiveTimeout( 1000); 
	            }
	            catch (UnsupportedCommOperationException ucoe) 
	            { 
		            // Ignore 
	            }

	            return new SerialPortServer( cpi, tcpPort);
            }
            catch(PortInUseException piue)
            {
                throw piue;
            }
            catch(Exception e)
            {
                // let this drop down below and throw the Exception...
            }
		}
        throw new UnsupportedCommOperationException("Port " + commPortName + " is not supported.");
	}

	public static void main( String[] args)
	throws UnsupportedCommOperationException, NoSuchPortException, PortInUseException
	{
		System.out.println( "CommPortServer v1.0");

		if( args.length == 0)
		{
			System.out.println();
			System.out.println( "Usage: CommPortServer COMM_PORT [TCP_PORT]");
			return;
		}

		int tcpPort = DEFAULT_TCP_PORT;
		if( args.length > 1)
		{
			try { tcpPort = Integer.decode( args[1]).intValue(); }
			catch( NumberFormatException nfe) { /* Ignore */ }
		}
		createPortServer( args[0], tcpPort).run();
	}

	protected final static int STOPPED = 0;
	protected final static int STOPPING = 1;
	protected final static int RUNNING = 2;
	protected final static int CONNECTED = 3;

	protected int state = STOPPED;

	protected int tcpPort;
	protected CommPortIdentifier commPortIdentifier;
	
	protected static CommPort cp;
	protected static InputStream cpis;
	protected static OutputStream cpos;

	protected Socket controlSocket;
	protected Socket streamSocket;
	protected Socket eventSocket;
    protected DataInputStream streamSocketInputStream;
    protected DataOutputStream streamSocketOutputStream;
    protected DataInputStream eventSocketInputStream;
    protected DataOutputStream eventSocketOutputStream;


	protected StreamConnector commToSocketConnector;
	protected StreamConnector socketToCommConnector;

	private static final boolean DEBUG = true;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -