6.5. TCP Server Setup¶
6.5.1. Dependencies¶
TCP server setup requires the NET
foundation library.
To setup a server, add the following dependency to your project’s module.ivy
file:
<dependency org="ej.api" name="net" rev="1.1.2" />
6.5.2. Replacing the javax.microedition.io.ServerSocketConnection
class¶
Code using javax.microedition.io.ServerSocketConnection
can use java.net.ServerSocket
instead.
6.5.2.1. Code sample¶
The following snippet is extracted from the J2ME Javadoc.
// Create the server listening socket for port 1234
ServerSocketConnection scn = (ServerSocketConnection)
Connector.open("socket://:1234");
// Wait for a connection.
SocketConnection sc = (SocketConnection) scn.acceptAndOpen();
// Set application specific hints on the socket.
sc.setSocketOption(DELAY, 0);
sc.setSocketOption(LINGER, 0);
sc.setSocketOption(KEEPALIVE, 0);
sc.setSocketOption(RCVBUF, 128);
sc.setSocketOption(SNDBUF, 128);
// Get the input stream of the connection.
DataInputStream is = sc.openDataInputStream();
// Get the output stream of the connection.
DataOutputStream os = sc.openDataOutputStream();
// Read the input data.
String result = is.readUTF();
// Echo the data back to the sender.
os.writeUTF(result);
// Close everything.
is.close();
os.close();
sc.close();
scn.close();
It can be adapted as follows:
// Create the server listening socket for port 1234
ServerSocket scn = new ServerSocket(1234);
// Wait for a connection.
Socket sc = scn.accept();
// Set application specific hints on the socket.
sc.setTcpNoDelay(true);
sc.setSoLinger(false, 0);
sc.setKeepAlive(false);
sc.setReceiveBufferSize(128);
sc.setSendBufferSize(128);
// Get the input stream of the connection.
DataInputStream is = new DataInputStream(sc.getInputStream());
// Get the output stream of the connection.
DataOutputStream os = new DataOutputStream(sc.getOutputStream());
// Read the input data.
String result = is.readUTF();
// Echo the data back to the sender.
os.writeUTF(result);
// Close everything.
is.close();
os.close();
sc.close();
scn.close();