当前位置: 首页 > 学习 > 电脑学习 > 程序设计 > JAVA > WEBSERVICE > 正文

Java套接字编程(5)

http://www.zk168.com.cn  招考学习网 2006-4-11 2:34:40
-----------------------------------------------------------[交流]-[打印]-[发送]-[收藏]--
Java套接字编程(5)

DatagramSocket类

   DatagramSocket类在客户端创建自寻址套接字与服务器端进行通信连接,并发送和接受自寻址套接字。虽然有多个构造函数可供选择,但我发现创建客户端自寻址套接字最便利的选择是DatagramSocket()函数,而服务器端则是DatagramSocket(int port)函数,如果未能创建自寻址套接字或绑定自寻址套接字到本地端口,那么这两个函数都将抛出一个SocketException对象,一旦程序创建了DatagramSocket对象,那么程序分别调用send(DatagramPacket dgp)和 receive(DatagramPacket dgp)来发送和接收自寻址数据包,

   List4显示的DGSClient源代码示范了如何创建自寻址套接字以及如何通过套接字处理发送和接收信息

Listing 4: DGSClient.java
// DGSClient.java

import java.io.*;
import java.net.*;

class DGSClient
{
  public static void main (String [] args)
  {
   String host = "localhost";

   // If user specifies a command-line argument, that argument
   // represents the host name.

   if (args.length == 1)
    host = args [0];

   DatagramSocket s = null;

   try
   {
    // Create a datagram socket bound to an arbitrary port.

    s = new DatagramSocket ();

    // Create a byte array that will hold the data portion of a
    // datagram packet's message. That message originates as a
    // String object, which gets converted to a sequence of
    // bytes when String's getBytes() method is called. The
    // conversion uses the platform's default character set.

    byte [] buffer;
    buffer = new String ("Send me a datagram").getBytes ();

    // Convert the name of the host to an InetAddress object.
    // That object contains the IP address of the host and is
    // used by DatagramPacket.

    InetAddress ia = InetAddress.getByName (host);

    // Create a DatagramPacket object that encapsulates a
    // reference to the byte array and destination address
    // information. The destination address consists of the
    // host's IP address (as stored in the InetAddress object)
    // and port number 10000 -- the port on which the server
    // program listens.

    DatagramPacket dgp = new DatagramPacket (buffer,
         buffer.length,
         ia,
         10000);

    // Send the datagram packet over the socket.

    s.send (dgp);

    // Create a byte array to hold the response from the server.
    // program.

    byte [] buffer2 = new byte [100];

    // Create a DatagramPacket object that specifies a buffer
    // to hold the server program's response, the IP address of
    // the server program's computer, and port number 10000.

    dgp = new DatagramPacket (buffer2,
       buffer.length,
       ia,
       10000);

    // Receive a datagram packet over the socket.

    s.receive (dgp);

    // Print the data returned from the server program and stored
    // in the datagram packet.

    System.out.println (new String (dgp.getData ()));

   }
   catch (IOException e)
   {
    System.out.println (e.toString ());
   }
   finally
   {
    if (s != null)
     s.close (); 
   }
  }
}

   DGSClient由创建一个绑定任意本地(客户端)端口好的DatagramSocket对象开始,然后装入带有文本信息的数组buffer和描述服务器主机IP地址的InetAddress子类对象的引用,接下来,DGSClient创建了一个DatagramPacket对象,该对象加入了带文本信息的缓冲器的引用,InetAddress子类对象的引用,以及服务端口号10000, DatagramPacket的自寻址数据包通过方法sent()发送给服务器程序,于是一个包含服务程序响应的新的DatagramPacket对象被创建,receive()得到响应的自寻址数据包,然后自寻址数据包的getData()方法返回该自寻址数据包的一个引用,最后关闭DatagramSocket。

   DGSServer服务程序补充了DGSClient的不足,List5是DGSServer的源代码:

Listing 5: DGSServer.java
// DGSServer.java

import java.io.*;
import java.net.*;

class DGSServer
{
  public static void main (String [] args) throws IOException
  {
   System.out.println ("Server starting ...\n");

   // Create a datagram socket bound to port 10000. Datagram
   // packets sent from client programs arrive at this port.

   DatagramSocket s = new DatagramSocket (10000);

   // Create a byte array to hold data contents of datagram
   // packet.

   byte [] data = new byte [100];

   // Create a DatagramPacket object that encapsulates a reference
   // to the byte array and destination address information. The
   // DatagramPacket object is not initialized to an address
   // because it obtains that address from the client program.

   DatagramPacket dgp = new DatagramPacket (data, data.length);

   // Enter an infinite loop. Press Ctrl+C to terminate program.

   while (true)
   {
    // Receive a datagram packet from the client program.

    s.receive (dgp);

    // Display contents of datagram packet.

    System.out.println (new String (data));

    // Echo datagram packet back to client program.

   s.send (dgp);
  }
}
}

   DGSServer创建了一个绑定端口10000的自寻址套接字,然后创建一个字节数组容纳自寻址信息,并创建自寻址包,下一步,DGSServer进入一个无限循环中以接收自寻址数据包、显示内容并将响应返回客户端,自寻址套接没有关闭,因为循环是无限的。

   在编译DGSServer 和DGSClient的源代码后,由输入java DGSServer开始运行DGSServer,然后在同一主机上输入Java DGSClient开始运行DGSClient,如果DGSServer与DGSClient运行于不同主机,在输入时注意要在命令行加上服务程序的主机名或IP地址,如:java DGSClient www.ddvip.net

(未完待续)
-----------------------------------------------------------[交流]-[打印]-[发送]-[收藏]--
最新入库:
 
·实质、过程及意义——阿多尔诺“否定的辩证法”探微
·从Ontology的译名之争看哲学术语的翻译原则
·论马克思主义哲学经典的解释——解释学方法及其在马克
·中国哲学当前的核心与周边问题
·和合学与21世纪文化价值和科技
·中国文化的和合精神与21世纪
·宗教之间理当相互宽容
·上半个世纪的自由主义
·殷周至春秋时期神人关系之演进
·大学之道:构建以“三纲八目”为核心的道德修养体系
相关内容:
 
·环保企业人力资源开发与管理的实证研究————巨龙公
·重油制气污水处理系统(A/O)技术改造
·英美CPA管理模式及其启示
·改造NERA微波公务信道为国产监控信道
·EAStudio让电子商务网站如虎添翼
·基于PB6和ORACLE8开发“劳动信息管理系统”
·巧解Pretty  Park 病毒一例
·CDMA在中国的应用以及向CDMA2000的过度中的问题研究
·SMA施工控制与现场监理
·浅谈改性沥青及SMA路面平整度的控制
网友点评:
 
会员名称:
密码:匿名 ·注册·忘记密码?
评论内容:
(最多300个字符)
  查看评论
友情提醒:
 1.库中的资料大都来自互联网、网友上传、各类书籍,在录入的过程中难免会出现错误,恳请网
 友来信指正!
 2.如果网友在本库中未能找到所需要的材料,请登陆到我们的论坛《招考学习网》版块!
 3.考友想加入招考学习网的编辑部,请发信到XueXiWang#Gmail.com(#改为@)附带个人简历
 4.如需转载请注明出处及作者,谢谢合作!
 5.如果您有更好的建议或意见请EMAIL:XueXiWang#Gmail.com (#改为@)
 6.凡标题中有注有“[NO]”字样均不含答案且答案整理中.
 7.如本库中转载文章涉及版权等问题,请相关网站或作者在两周内发邮件通知(EMAIL:  XueXiWang#Gmail.com (#改为@))我们,我们接到通知后立即删除该文章及链接!
你问我答 更多>>