王朝网络
分享
 
 
 

Java网络编程基础(二) Socket类的使用方法

王朝java/jsp·作者佚名  2008-10-30
宽屏版  字体: |||超大  

当客户程序需要与服务器程序通讯的时候,客户程序在客户机创建一个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

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

// Send the PAUSE command to the server. This allows several

// clients to start and verifies that the server is spawning

// multiple threads.

pw.println ("PAUSE");

// Send the DOW command to the server.

pw.println ("DOW");

// Obtain and print the current day of week.

System.out.println (br.readLine ());

// Send the DOM command to the server.

pw.println ("DOM");

// Obtain and print the current day of month.

System.out.println (br.readLine ());

// Send the DOY command to the server.

pw.println ("DOY");

// Obtain and print the current day of year.

System.out.println (br.readLine ());

}

catch (IOException e)

{

System.out.println (e.toString ());

}

finally

{

try

{

if (br != null)

br.close ();

if (pw != null)

pw.close ();

if (s != null)

s.close ();

}

catch (IOException e)

{

}

}

}

}

运行这段程序将会得到下面的结果:

Tue Jan 29 18:11:51 CST 2002

TUESDAY

29

29

SSClient创建了一个Socket对象与运行在主机端口10000的服务程序联系,主机的IP地址由host变量确定。SSClient将获得Socket的输入输出流,围绕BufferedReader的输入流和PrintWriter的输出流对字符串进行读写操作就变得非常容易,SSClient个服务程序发出各种date/time命令并得到响应,每个响应均被打印,一旦最后一个响应被打印,将执行Try/Catch/Finally结构的Finally子串,Finally子串将在关闭Socket之前关闭BufferedReader 和 PrintWriter。

在SSClient源代码编译完成后,可以输入java SSClient 来执行这段程序,如果有合适的程序运行在不同的主机上,采用主机名/IP地址为参数的输入方式,比如www.sina.com.cn是运行服务器程序的主机,那么输入方式就是java SSClient www.sina.com.cn

技巧

Socket类包含了许多有用的方法。比如getLocalAddress()将返回一个包含客户程序IP地址的InetAddress子类对象的引用;getLocalPort()将返回客户程序的端口号;getInetAddress()将返回一个包含服务器IP地址的InetAddress子类对象的引用;getPort()将返回服务程序的端口号。

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
>>返回首页<<
推荐阅读
 
 
频道精选
 
静静地坐在废墟上,四周的荒凉一望无际,忽然觉得,凄凉也很美
© 2005- 王朝网络 版权所有