|
//Createtheserverlisteningsocketforport1234
ServerSocketConnectionscn=(ServerSocketConnection)
Connector.open("socket://:1234");
//Waitforaconnection.
SocketConnectionsc=(SocketConnection)scn.acceptAndOpen();
//Setapplicationspecifichintsonthesocket.
sc.setSocketOption(DELAY,0);
sc.setSocketOption(LINGER,0);
sc.setSocketOption(KEEPALIVE,0);
sc.setSocketOption(RCVBUF,128);
sc.setSocketOption(SNDBUF,128);
//Gettheinputstreamoftheconnection.
DataInputStreamis=sc.openDataInputStream();
//Gettheoutputstreamoftheconnection.
DataOutputStreamos=sc.openDataOutputStream();
//Readtheinputdata.
Stringresult=is.readUTF();
//Echothedatabacktothesender.
os.writeUTF(result);
//Closeeverything.
is.close();
os.close();
sc.close();
scn.close();
..
SocketConnection的使用也是非常简单,通过Connector的open方法我们可以得到一个SocketConnection的实例。
SocketConnectionsc=(SocketConnection)
Connector.open("socket://host.com:79");
sc.setSocketOption(SocketConnection.LINGER,5);
InputStreamis=sc.openInputStream();
OutputStreamos=sc.openOutputStream();
os.write("\r\n".getBytes());
intch=0;
while(ch!=-1){
ch=is.read();
}
is.close();
os.close();
sc.close();
其实我们在用socket编写程序的时候无非遵循这样的一种规则:服务器端建立监听端口等待连接,客户端通过open()方法与服务器端建立连接,两端通过建立的socket传输数据,关闭连接。
|