// 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(); ..
SocketConnection的使用也是非常简单,通过Connector的open方法我们可以得到一个SocketConnection的实例。 SocketConnection sc = (SocketConnection) Connector.open("socket://host.com:79"); sc.setSocketOption(SocketConnection.LINGER, 5);
InputStream is = sc.openInputStream(); OutputStream os = sc.openOutputStream();
os.write("\r\n".getBytes()); int ch = 0; while(ch != -1) { ch = is.read(); }
is.close(); os.close(); sc.close(); |