Class Socket

  • All Implemented Interfaces:
    java.io.Closeable, java.lang.AutoCloseable
    Direct Known Subclasses:
    SSLSocket

    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("www.totalcross.com", 80);
     DataStream ds = new DataStream(socket);
     ds.writeBytes("GET / HTTP/1.0\n\n");
     String ack = socket.readLine();
     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, but CAN in the initUI method.

    When using GPRS connections, it is very important that you set a big timeout (20 seconds at least), otherwise the connection will be closed before the data is fully flushed (which only occurs after Socket.close).

    • Constructor Summary

      Constructors 
      Modifier Constructor Description
      protected Socket()
      For internal use only
        Socket​(java.lang.String host, int port)
      Opens a socket with the given host, port and open timeout of 1500ms.
        Socket​(java.lang.String host, int port, int timeout)
      Opens a socket with the given host, port, open timeout.
        Socket​(java.lang.String host, int port, int timeout, boolean noLinger)
      Opens a socket with the given host, port, timeout and linger option.
        Socket​(java.lang.String host, int port, int timeout, java.lang.String params)
      Opens a socket with the given parameters.
    • Field Detail

      • readTimeout

        public int readTimeout
        Stores 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 read timeout is 5000 milliseconds.
      • writeTimeout

        public int writeTimeout
        Stores the timeout value for write operations. The value specifies the number of milliseconds to wait from the time of last activity before timing out a write operation. Passing a value of 0 sets no timeout causing any write operation to return immediately, successfully or not. The default write timeout is 2000 milliseconds.
      • DEFAULT_OPEN_TIMEOUT

        public static final int DEFAULT_OPEN_TIMEOUT
        Default timeout value for socket creation
        See Also:
        Constant Field Values
      • DEFAULT_READ_TIMEOUT

        public static final int DEFAULT_READ_TIMEOUT
        Default timeout value for read operations
        See Also:
        Constant Field Values
      • DEFAULT_WRITE_TIMEOUT

        public static final int DEFAULT_WRITE_TIMEOUT
        Default timeout value for write operations
        See Also:
        Constant Field Values
    • Constructor Detail

      • Socket

        protected Socket()
        For internal use only
      • Socket

        public Socket​(java.lang.String host,
                      int port,
                      int timeout,
                      java.lang.String params)
               throws UnknownHostException,
                      IOException
        Opens a socket with the given parameters. 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 specified timeout, in milliseconds.
        params - the string specifying additional parameters to this socket. Each parameter is specified in a 'key=value' form and separated by a ';' from the next parameter. For example: 'p1=v1;p2=v2'. On BlackBerry, the following parameters are valid: 'apn=[value]', 'apnuser=[value]', 'apnpass=[value]', 'directtcp=[true|false]' and 'nolinger=[true|false]'. On Palm OS devices, the only valid parameter is 'nolinger=[true| false]'. 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.
        Throws:
        UnknownHostException
        IOException
      • Socket

        public Socket​(java.lang.String host,
                      int port,
                      int timeout,
                      boolean noLinger)
               throws UnknownHostException,
                      IOException
        Opens a socket with the given host, port, timeout and linger option.
        Parameters:
        host - the host name or IP address to connect to
        port - the port number to connect to
        timeout - the specified timeout, in milliseconds.
        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.
        Throws:
        UnknownHostException
        IOException
        See Also:
        Socket(String, int, int, String)
    • Method Detail

      • close

        public void close()
                   throws IOException
        Closes the socket.
        Specified by:
        close in interface java.lang.AutoCloseable
        Specified by:
        close in interface java.io.Closeable
        Throws:
        IOException - If the socket is closed more than once
      • readBytes

        public int readBytes​(byte[] buf,
                             int start,
                             int count)
                      throws IOException
        Reads bytes from the socket into a byte array. 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.
        Specified by:
        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
        Returns:
        The number of bytes actually read; or <= 0 if no data is available; or -1 if the server closed the connection or an error prevented the read operation from occurring.
        Throws:
        IOException
      • readBytes

        public int readBytes​(byte[] buf)
                      throws IOException
        Reads bytes from the socket into a byte array, from offset 0 to buf.length. 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.
        Parameters:
        buf - the byte array to read data into
        Returns:
        The number of bytes actually read; or <= 0 if no data is available; or -1 if the server closed the connection or an error prevented the read operation from occurring.
        Throws:
        IOException
        Since:
        SuperWaba 5.6
        See Also:
        readBytes(byte[], int, int)
      • writeBytes

        public int writeBytes​(byte[] buf,
                              int start,
                              int count)
                       throws IOException
        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.
        Specified by:
        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
        Returns:
        the number of bytes actually written
        Throws:
        IOException
      • readLine

        public java.lang.String readLine()
                                  throws IOException
        Reads a line of text from this socket. Any char lower than space is considered a new line separator. This method correctly handles newlines with \\n or \\r\\n.

        Note: this method is VERY slow since it reads a single character per time. Consider using new LineReader(socket) or new BufferedStream(socket) instead.
        Returns:
        the read line or null if nothing was read.
        Throws:
        IOException
        Since:
        SuperWaba 5.61
        See Also:
        LineReader, BufferedStream
      • finalize

        protected void finalize()
        Overrides:
        finalize in class java.lang.Object
      • getNativeSocket

        public java.lang.Object getNativeSocket()
        Used internally by the SSL classes. Not available at the device.
      • getHost

        public java.lang.String getHost()
        Returns the remote host which this socket is connected to, passed in the constructor.
      • getPort

        public int getPort()
        Returns the remote port which this socket is connected to, passed in the constructor.