欢迎来到天天文库
浏览记录
ID:15778850
大小:39.00 KB
页数:6页
时间:2018-08-05
《java网络编程基础 socket类的使用方法》由会员上传分享,免费在线阅读,更多相关内容在学术论文-天天文库。
1、当客户程序需要与服务器程序通讯的时候,客户程序在客户机创建一个socket对象,Socket类有几个构造函数。两个常用的构造函数是Socket(InetAddressaddr,intport)和Socket(Stringhost,intport),两个构造函数都创建了一个基于Socket的连接服务器端流套接字的流套接字。对于第一个InetAddress子类对象通过addr参数获得服务器主机的IP地址,对于第二个函数host参数包被分配到InetAddress对象中,如果没有IP地址与host参数相一
2、致,那么将抛出UnknownHostException异常对象。两个函数都通过参数port获得服务器的端口号。假设已经建立连接了,网络API将在客户端基于Socket的流套接字中捆绑客户程序的IP地址和任意一个端口号,否则两个函数都会抛出一个IOException对象。如果创建了一个Socket对象,那么它可能通过调用Socket的getInputStream()方法从服务程序获得输入流读传送来的信息,也可能通过调用Socket的getOutputStream()方法获得输出流来发送消息。在读写活动
3、完成之后,客户程序调用close()方法关闭流和流套接字,下面的代码创建了一个服务程序主机地址为198.163.227.6,端口号为13的Socket对象,然后从这个新创建的Socket对象中读取输入流,然后再关闭流和Socket对象。Sockets=newSocket("198.163.227.6",13);InputStreamis=s.getInputStream();//Readfromthestream.is.close();s.close();接下面我们将示范一个流套接字的客户程序,这个
4、程序将创建一个Socket对象,Socket将访问运行在指定主机端口10000上的服务程序,如果访问成功客户程序将给服务程序发送一系列命令并打印服务程序的响应。List2使我们创建的程序SSClient的源代码:Listing2:SSClient.java//SSClient.javaimportjava.io.*;importjava.net.*;classSSClient{ publicstaticvoidmain(String[]args) { Stringhost="localhost";
5、 //Ifuserspecifiesacommand-lineargument,thatargument //redivsentsthehostname. if(args.length==1) host=args[0]; BufferedReaderbr=null; PrintWriterpw=null; Sockets=null; try { //Createasocketthatattemptstoconnecttotheserver //programontheho
6、statport10000. s=newSocket(host,10000); //Createaninputstreamreaderthatchainstothesocket's //byte-orientedinputstream.Theinputstreamreader //convertsbytesreadfromthesockettocharacters.The //conversionisbasedontheplatform'sdefaultcharacter /
7、/set. InputStreamReaderisr; isr=newInputStreamReader(s.getInputStream()); //Createabufferedreaderthatchainstotheinputstream //reader.Thebufferedreadersuppliesaconvenientmethod //forreadingentirelinesoftext. br=newBufferedReader(isr); //Cr
8、eateaprintwriterthatchainstothesocket'sbyte- //orientedoutputstream.Theprintwritercreatesan //intermediateoutputstreamwriterthatconverts //characterssenttothesockettobytes.Theconversion //isbasedontheplatform'sdefaultcharacterse
此文档下载收益归作者所有