快速业务通道

Java语言的Socket类 - 编程入门网

作者 佚名技术 来源 NET编程 浏览 发布时间 2012-06-17

Java语言的Socket类

时间:2011-04-23

当客户程序需要与服务器程序通讯的时候,客户程序在客户机创建一个socket对象,Socket类有几个构造函数。两个常用的构造函数是 Socket(InetAddress addr, int port) 和 Socket(String host, int port),两个构造函数都创建了一个基于Socket的连接服务器端流套接字的流套接字。对于第一个InetAddress子类对象通过addr参数获得服务器主机的IP地址,对于第二个函数host参数包被分配到InetAddress对象中,如果没有IP地址与host参数相一致,那么将抛出UnknownHostException异常对象。两个函数都通过参数port获得服务器的端口号。假设已经建立连接了,网络API将在客户端基于Socket的流套接字中捆绑客户程序的IP地址和任意一个端口号,否则两个函数都会抛出一个IOException对象。

如果创建了一个Socket对象,那么它可能通过调用Socket的 getInputStream()方法从服务程序获得输入流读传送来的信息,也可能通过调用Socket的 getOutputStream()方法获得输出流来发送消息。在读写活动完成之后,客户程序调用close()方法关闭流和流套接字,下面的代码创建了一个服务程序主机地址为198.163.227.6,端口号为13的Socket对象,然后从这个新创建的Socket对象中读取输入流,然后再关闭流和Socket对象。

Socket s = new Socket ("198.163.227.6", 13); InputStream is = s.getInputStream (); // Read from the stream. is.close (); s.close ();

接下面我们将示范一个流套接字的客户程序,这个程序将创建一个Socket对象,Socket将访问运行在指定主机端口10000上的服务程序,如果访问成功客户程序将给服务程序发送一系列命令并打印服务程序的响应。List2使我们创建的程序SSClient的源代码:

Listing 2: SSClient.java // SSClient.java import java.io.*; import java.net.*; class SSClient {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]; BufferedReader br = null; PrintWriter pw = null; Socket s = null; try {// Create a socket that attempts to connect to the server   // program on the host at port 10000.   s = new Socket (host, 10000);   // Create an input stream reader that chains to the socket′s   // byte-oriented input stream. The input stream reader   // converts bytes read from the socket to characters. The   // conversion is based on the platform′s default character   // set.   InputStreamReader isr;   isr = new InputStreamReader (s.getInputStream ());   // Create a buffered reader that chains to the input stream   // reader. The buffered reader supplies a convenient method   // for reading entire lines of text.   br = new BufferedReader (isr);   // Create a print writer that chains to the socket′s byte-   // oriented output stream. The print writer creates an   // intermediate output stream writer that converts   // characters sent to the socket to bytes. The conversion   // is based on the platform′s default character set.   pw = new PrintWriter (s.getOutputStream (), true);   // Send the DATE command to the server.   pw.println ("DATE");   // Obtain and print the current date/time.   System.out.println (br.readLine

凌众科技专业提供服务器租用、服务器托管、企业邮局、虚拟主机等服务,公司网站:http://www.lingzhong.cn 为了给广大客户了解更多的技术信息,本技术文章收集来源于网络,凌众科技尊重文章作者的版权,如果有涉及你的版权有必要删除你的文章,请和我们联系。以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!

分享到: 更多

Copyright ©1999-2011 厦门凌众科技有限公司 厦门优通互联科技开发有限公司 All rights reserved

地址(ADD):厦门软件园二期望海路63号701E(东南融通旁) 邮编(ZIP):361008

电话:0592-5908028 传真:0592-5908039 咨询信箱:web@lingzhong.cn 咨询OICQ:173723134

《中华人民共和国增值电信业务经营许可证》闽B2-20100024  ICP备案:闽ICP备05037997号