📄 commportserver.java
字号:
package com.eta.etatcpcomm.server;
import java.io.*;
import java.net.*;
import javax.comm.*;
import com.eta.etatcpcomm.*;
/* This class allows us to perform operations on the CommPort object that this
* server is talking to. It also listens for connections on port 10101 (or
* whatever is specified) and begins a communication session if such a
* connection is made.
*/
public abstract class CommPortServer implements Runnable, Constants
{
protected CommPortServer(CommPortIdentifier commPortIdentifier, int tcpPort)
{
this.commPortIdentifier = commPortIdentifier;
this.tcpPort = tcpPort;
}
public abstract int getPortType();
// Provides access to the underlying CommPort.
public CommPort getCommPort()
{
return cp;
}
public synchronized void stop()
{
if( state != STOPPED && state != STOPPING)
{
setState( STOPPING);
}
}
/* Method to be overridden by subclass, if necessary.
* Called once in the lifetime of the process.
*/
public void addListeners()
{
}
public void run()
{
ServerSocket ss = null;
try
{
//add any listeners for the SerialPort
addListeners();
ss = new ServerSocket( tcpPort);
// Setting SO_TIMEOUT allows us to check for termination
// requests every so often.
ss.setSoTimeout( 5000);
}
catch( IOException ioe)
{
return;
}
try
{
setState( RUNNING);
while( state == RUNNING)
{
controlSocket = null;
try
{
//use this object array to gather up the DataInputStreams,
//that way we only have to create them once
Object[] datastreams = new Object[2];
// Listen for control socket connection
if( DEBUG) System.out.println( "Listening for control socket");
controlSocket = accept(ss, 0, datastreams);
if( DEBUG) System.out.println( "Got control socket");
controlSocket.setTcpNoDelay( true);
// Use double KEEP_ALIVE_TIME to allow for latency
controlSocket.setSoTimeout(2 * KEEP_ALIVE_TIME);
// Get control streams
//DataInputStream cis = (DataInputStream) datastreams[0];
//DataOutputStream cos = (DataOutputStream) datastreams[1];
// Get new control streams
DataInputStream cis = new DataInputStream(cpis);
DataOutputStream cos = new DataOutputStream(cpos);
cis.readLine datastreams[0].toString();
// Send port type
cos.writeInt( getPortType());
// Read status and restart loop if it is not OK
if( OK != cis.readInt())
{
controlSocket.close();
continue;
}
try
{
initialize(ss);
}
catch( PortInUseException piue)
{
// Send exception
cos.writeInt(PORT_IN_USE_EXCEPTION);
continue;
}
catch( IOException ioe)
{
// Send exception
cos.writeInt(IO_EXCEPTION);
continue;
}
// Send OK
cos.writeInt(OK);
// Set state to CONNECTED
setState(CONNECTED);
// Handle connection
handleConnection(cis, cos);
}
catch( IOException ioe)
{
// Assume connection has been terminated and no longer
// needs to be handled.
if( DEBUG) System.out.println( "Caught IOException. Terminating connection.");
// Step down to RUNNING state IFF current state is CONNECTED
synchronized( this)
{
if( state == CONNECTED)
{
setState( RUNNING);
}
}
}
// Stop on any other Exception.
catch( Exception e)
{
if( DEBUG) e.printStackTrace();
stop();
}
finally
{
// Close any and all sockets that may have been opened
if( DEBUG) System.out.println( "Closing connection...");
close();
if( DEBUG) System.out.println( "...Connection closed.");
}
}
if( DEBUG) System.out.println( "RUNNING != state (" + state + ")" );
}
catch( RuntimeException re)
{
throw re;
}
finally
{
try
{
ss.close();
}
catch( IOException ioe) { /* Ignore */ }
if( DEBUG) System.out.println( "Setting state to STOPPED.");
setState( STOPPED);
if( DEBUG) System.out.println( "CPS.run() returning...");
}
if( DEBUG) System.out.println( "...return is normal.");
}
protected synchronized void setState(int state)
{
if( DEBUG) System.out.println( "CommPortServer state change " + this.state + "->" + state);
this.state = state;
notifyAll();
}
protected void initialize( ServerSocket ss) throws IOException, PortInUseException
{
// Open comm port
if (DEBUG) System.out.println( "Opening comm port");
/* try this...we are going to open the serial port upon construction
of the server, and not close it until the end...if we ever want to
open the server only when there is a request, this is where we
need to do it
cp = commPortIdentifier.open( "tcpcomm", 0);
however, we should reset the commPort to default parameters...
*/
try
{
((SerialPort)cp).setSerialPortParams(2400, 8, 1, SerialPort.PARITY_EVEN);
((SerialPort)cp).setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
}
catch(UnsupportedCommOperationException ucoe)
{
//this should not happen on TINI...these are the default params...
}
try
{
cp.enableReceiveTimeout( 3000);
}
catch (UnsupportedCommOperationException ucoe)
{
// Ignore
}
if (DEBUG) System.out.println( "Got comm port");
// Set receive timeout to 1 second
if( DEBUG) System.out.println( "Setting receive timeout to 1 second.");
try
{
Object[] datastreams = new Object[2];
// Get stream socket
if( DEBUG) System.out.println( "Listening for streamSocket");
streamSocket = accept( ss, STREAM_ID | controlSocket.getPort(), datastreams);
streamSocketInputStream = (DataInputStream) datastreams[0];
streamSocketOutputStream = (DataOutputStream) datastreams[1];
if( DEBUG) System.out.println( "Got stream socket");
streamSocket.setTcpNoDelay( true);
// Get event socket
if( DEBUG) System.out.println( "Listening for eventSocket");
eventSocket = accept( ss, EVENT_ID | controlSocket.getPort(), datastreams);
eventSocketInputStream = (DataInputStream) datastreams[0];
eventSocketOutputStream = (DataOutputStream) datastreams[1];
if( DEBUG) System.out.println( "Got event socket");
eventSocket.setTcpNoDelay( true);
}
catch( IOException ioe)
{
System.out.println("EXCEPTION IN INITIALIZE: "+ioe);
cp.close();
throw ioe;
}
}
/* Once we have a connection we go here, and wait for requests from the client.
* When we get requests, we perform them--they will be things like setDTR to
* true, set baud rate to 9600, etc.
*/
protected void handleConnection( DataInputStream cis, DataOutputStream cos) throws IOException
{
while( state == CONNECTED)
{
try
{
if( DEBUG) System.out.println( "----------");
int cmd = cis.readInt();
handleRequest( cmd, cis, cos);
}
catch( UnsupportedCommOperationException ucoe)
{
cos.writeInt(UNSUPPORTED_COMM_OPERATION_EXCEPTION);
cos.writeUTF(ucoe.getMessage());
}
}
if( DEBUG) System.out.println( "CPS.handleConnection() returning normally.");
}
protected void handleRequest(int cmd, DataInputStream cis, DataOutputStream cos)
throws IOException, UnsupportedCommOperationException
{
int p0;
int retVal = 0;
switch( cmd)
{
case KEEP_ALIVE:
// Do nothing
break;
case GET_INPUT_STREAM:
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -