选择显示字体大小

j2me中使用socket开发联网程序(1)

j2me中基于udp协议编程一文中介绍了如何使用datagram和datagramconnection来开发应用程序,本文将主要讲述在midp2.0中使用serversocketconnection和socketconnection来开发联网应用程序。tcp协议是可以保证传输的质量的,这也是他和udp的一大区别。由于以上谈到的四个类都属于gcf,他们在程序编写方面也非常相似,通常我们在server端的某个端口监听,当客户端连接服务器的时候,则可以得到一个socketconnection的实例。通过两端的socketconnection则可以实现c/s结构的通信了。

首先看一下,serversocketconnection类,它的一个非常重要的方法就是acceptandopen()方法,这个方法返回一个socketconnection实例,从而使得客户端和服务器端可以通过socket通信了。典型的代码如下:

// 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();

其实我们在用socket编写程序的时候无非遵循这样的一种规则:服务器端建立监听端口等待连接,客户端通过open()方法与服务器端建立连接,两端通过建立的socket传输数据,关闭连接。

下图是我在运行wtk.networkdemo的时候的截图!代码也一并发表出来。


 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons