waba.io
Class Socket

java.lang.Object
  |
  +--waba.io.Stream
        |
        +--waba.io.Socket
Direct Known Subclasses:
SerialSocket

public class Socket
extends Stream

Socket is a TCP/IP network socket.

Under Java and Windows CE, if no network is present, the socket constructor may hang for an extended period of time due to the implementation of sockets in the underlying OS. This is a known problem.

Here is an example showing data being written and read from a socket:

 Socket socket = new Socket("http://www.superwaba.org", 80);
 if (!socket.isOpen())
   return;
 byte []bytes = "GET / HTTP/1.0\n\n".getBytes();
 socket.writeBytes(bytes,0,bytes.length);
 byte buf[] = new byte[10];
 int count = socket.readBytes(buf, 0, buf.length);
 if (count == buf.length)
    ...
 socket.close();
 
Important: you cannot open a socket before the main event loop. In other words, you cannot open a socket in the app's constructor, or even in the onStart method. The socket can only be openned after the onStart method finishes. You may setup a timer in the onStart that, when called, opens the socket. Or simply open the socket after a button press.


Field Summary
 int lastError
          Contains the last error caused by a method call on the PalmOS device only.
 boolean refreshBeforeEachRead
          If set to true, the function NetLibConnectionRefresh will be called before each read/write.
 
Constructor Summary
protected Socket()
          For internal use only
  Socket(String host, int port)
          Opens a socket.
  Socket(String host, int port, int timeout)
          Opens a socket.
  Socket(String host, int port, int timeout, boolean noLinger)
          Opens a socket.
 
Method Summary
 boolean close()
          Closes the socket.
static boolean disconnect()
          Disconects the socket.
 boolean isOpen()
          Returns true if the socket is open and false otherwise.
 int readBytes(byte[] buf, int start, int count)
          Reads bytes from the socket into a byte array.
 boolean setReadTimeout(int millis)
          Sets the timeout value for read operations.
 int writeBytes(byte[] buf, int start, int count)
          Writes to the socket.
 
Methods inherited from class java.lang.Object
equals, getClass, hashCode, notify, toString, wait, wait
 

Field Detail

lastError

public int lastError
Contains the last error caused by a method call on the PalmOS device only. Below is the errors that this can return (from NetMgr.h):

SW Custom codes (See nmpalm_wabaio.c for details):
65526 (-10): INVALID_HOST
65525 (-11): NO_NET_LIBRARY_AVAILABLE
65524 (-12): NET_NOT_READY_FOR_OPEN
65523 (-13): NET_NOT_OPENED_PROPERLY
65522 (-14): ARRAY_RANGE_CHECK

WindowsCE error codes: see winerror.h in the Windows SDK. Palm OS error codes.

Modem Error codes:
NoTone 4353
NoCarrier 4354
LineBusy 4355
UserCancelled 4356
CmdError 4357
NoModem 4358
OutOfMemory 4359
PrefsNotSetup 4360
DialStringErr 4361
mdmErrNoPhoneNum 4362

Net Error codes:
AlreadyOpen 4609
NotOpen 4610
StillOpen 4611
ParamErr 4612
NoMoreSockets 4613
OutOfResources 4614
OutOfMemory 4615
SocketNotOpen 4616
SocketBusy 4617
MessageTooBig 4618
SocketNotConnected 4619
NoInterfaces 4620
BufTooSmall 4621
Unimplemented 4622
PortInUse 4623
QuietTimeNotElapsed 4624
Internal 4625
Timeout 4626
SocketAlreadyConnected 4627
SocketClosedByRemote 4628
OutOfCmdBlocks 4629
WrongSocketType 4630
SocketNotListening 4631
UnknownSetting 4632
InvalidSettingSize 4633
PrefNotFound 4634
InvalidInterface 4635
InterfaceNotFound 4636
TooManyInterfaces 4637
BufWrongSize 4638
UserCancel 4639
BadScript 4640
NoSocket 4641
SocketRcvBufFull 4642
NoPendingConnect 4643
UnexpectedCmd 4644
NoTCB 4645
NilRemoteWindowSize 4646
NoTimerProc 4647
SocketInputShutdown 4648
CmdBlockNotCheckedOut 4649
CmdNotDone 4650
UnknownProtocol 4651
UnknownService 4652
UnreachableDest 4653
ReadOnlySetting 4654
WouldBlock 4655
AlreadyInProgress 4656
PPPTimeout 4657
PPPBroughtDown 4658
AuthFailure 4659
PPPAddressRefused 4660
DNSNameTooLong 4661
DNSBadName 4662
DNSBadArgs 4663
DNSLabelTooLong 4664
DNSAllocationFailure 4665
DNSTimeout 4666
DNSUnreachable 4667
DNSFormat 4668
DNSServerFailure 4669
DNSNonexistantName 4670
DNSNIY 4671
DNSRefused 4672
DNSImpossible 4673
DNSNoRRS 4674
DNSAborted 4675
DNSBadProtocol 4676
DNSTruncated 4677
DNSNoRecursion 4678
DNSIrrelevant 4679
DNSNotInLocalCache 4680
DNSNoPort 4681
IPCantFragment 4682
IPNoRoute 4683
IPNoSrc 4684
IPNoDst 4685
IPktOverflow 4686
TooManyTCPConnections 4687
NoDNSServers 4688
InterfaceDown 4689
NoChannel 4690
DieState 4691
ReturnedInMail 4692
ReturnedNoTransfer 4693
ReturnedIllegal 4694
ReturnedCongest 4695
ReturnedError 4696
ReturnedBusy 4697
GMANState 4698
QuitOnTxFail 4699
FlexListFull 4700
SenderMAN 4701
IllegalType 4702
IllegalState 4703
IllegalFlags 4704
IllegalSendlist 4705
IllegalMPAKLength 4706
IllegalAddressee 4707
IllegalPacketClass 4708
BufferLength 4709
NiCdLowBattery 4710
RFinterfaceFatal 4711
IllegalLogout 4712
AAARadioLoad 4713
AntennaDown 4714
NiCdCharging 4715
AntennaWentDown 4716
NotActivated 4717
RadioTemp 4718
NiCdChargeError 4729
NiCdSag 4720
NiCdChargeSuspend 4721
reserved 4722
ConfigNotFound 4723
ConfigCantDelete 4724
ConfigTooMany 4725
ConfigBadName 4726
ConfigNotAlias 4727
ConfigCantPointToAlias 4728
ConfigEmpty 4729
AlreadyOpenWithOtherConfig 4730
ConfigAliasErr 4731
NoMultiPktAddr 4732
OutOfPackets 4733
MultiPktAddrReset 4734
StaleMultiPktAddr 4735
ScptPluginMissing 4736
ScptPluginLaunchFail 4737
ScptPluginCmdFail 4738
ScptPluginInvalidCmd 4739
TelMissingComponent 4740
TelErrorNotHandled 4741


refreshBeforeEachRead

public boolean refreshBeforeEachRead
If set to true, the function NetLibConnectionRefresh will be called before each read/write. Note that in some tests this makes the read/write operation 3 times slower!
Constructor Detail

Socket

protected Socket()
For internal use only

Socket

public Socket(String host,
              int port)
Opens a socket. This method establishes a socket connection by looking up the given host and performing the 3 way TCP/IP handshake. The default timeout for opening the connection is 1.5 seconds and the default noLinger is false.
Parameters:
host - the host name or IP address to connect to
port - the port number to connect to

Socket

public Socket(String host,
              int port,
              int timeout)
Opens a socket. This method establishes a socket connection by looking up the given host and performing the 3 way TCP/IP handshake. The default noLinger is false;
Parameters:
host - the host name or IP address to connect to
port - the port number to connect to
timeout - the timeout (in ms) for opening the socket.

Socket

public Socket(String host,
              int port,
              int timeout,
              boolean noLinger)
Opens a socket. This method establishes a socket connection by looking up the given host and performing the 3 way TCP/IP handshake.
Parameters:
host - the host name or IP address to connect to
port - the port number to connect to
timeout - the timeout (in ms) for opening the socket. This should be 1500.
noLinger - if true, the socket is closed immediately, and no ack is waited from the server. Note that this must be done for the very first socket creation per application.
Method Detail

close

public boolean close()
Closes the socket. Returns true if the operation is successful and false otherwise.
Overrides:
close in class Stream

isOpen

public boolean isOpen()
Returns true if the socket is open and false otherwise. This can be used to check if opening the socket was successful. This method does not clear the lastError flag.
Overrides:
isOpen in class Stream

setReadTimeout

public boolean setReadTimeout(int millis)
Sets the timeout value for read operations. The value specifies the number of milliseconds to wait from the time of last activity before timing out a read operation. Passing a value of 0 sets no timeout causing any read operation to return immediately with or without data. The default timeout is 5000 milliseconds. This method returns true if successful and false if the value passed is negative or the socket is not open. The read timeout will have effect in the next read instruction.
Parameters:
millis - timeout in milliseconds.

readBytes

public int readBytes(byte[] buf,
                     int start,
                     int count)
Reads bytes from the socket into a byte array. Returns the number of bytes actually read or -1 if the server closed the connection or an error prevented the read operation from occurring. Note that in the device it may return with less bytes than requested. Note also that, if -1 is returned and the lastError is 4626, please insist 3 or 4 more times, because it may work.
Overrides:
readBytes in class Stream
Parameters:
buf - the byte array to read data into
start - the start position in the byte array
count - the number of bytes to read

writeBytes

public int writeBytes(byte[] buf,
                      int start,
                      int count)
Writes to the socket. Returns the number of bytes written or -1 if an error prevented the write operation from occurring. If data can't be written to the socket for approximately 2 seconds, the write operation will time out.
Overrides:
writeBytes in class Stream
Parameters:
buf - the byte array to write data from
start - the start position in the byte array
count - the number of bytes to write

disconnect

public static boolean disconnect()
Disconects the socket. This may hangup the modem or disconect the attached device