JAVA22.docx
《JAVA22.docx》由会员分享,可在线阅读,更多相关《JAVA22.docx(18页珍藏版)》请在冰豆网上搜索。
JAVA22
第二十二课网络编程
案例:
2201URL应用举例
案例文件:
URLReader.java
目标:
使用URL类,体会网络网络数据传输
代码:
/*范例名称:
URL应用举例
*源文件名称:
URLReader.java
*要点:
*1.URL概念及URL类的使用
*2.URL类的openStream()及其它方法
*/
importjava.io.*;
import.*;
publicclassURLReader{
publicstaticvoidmain(Stringargs[]){
try{
URLtirc=newURL("
BufferedReaderin=newBufferedReader(new
InputStreamReader(tirc.openStream()));
Strings;
while((s=in.readLine())!
=null)
System.out.println(s);
in.close();
}catch(MalformedURLExceptione){
System.out.println(e);
}catch(IOExceptione){
System.out.println(e);
}
}
}
案例:
2202简单的client/server程序
案例文件:
TestServer.java/TestClient.java
目标:
掌握JavaSocket编程机制及其实现
代码:
/*范例名称:
简单的client/server程序
*源文件名称:
TestClient.java/TestServer.java
*要点:
*1.JavaSocket编程步骤
*2.Socket/ServerSocket类用法
*3.通过Socket对象可以获取通信对方Socket的信息
*/
//文件TestServer.java
import.*;
importjava.io.*;
publicclassTestServer{
publicstaticvoidmain(Stringargs[]){
try{
ServerSockets=newServerSocket(8888);
while(true){
Sockets1=s.accept();
OutputStreamos=s1.getOutputStream();
DataOutputStreamdos=newDataOutputStream(os);
dos.writeUTF("Hello,"+s1.getInetAddress()+
"port#"+s1.getPort()+"bye-bye!
");
dos.close();
s1.close();
}
}catch(IOExceptione){
System.out.println("程序运行出错:
"+e);
}
}
}
//文件TestClient.java
import.*;
importjava.io.*;
publicclassTestClient{
publicstaticvoidmain(Stringargs[]){
try{
Sockets1=newSocket("127.0.0.1",8888);
InputStreamis=s1.getInputStream();
DataInputStreamdis=newDataInputStream(is);
System.out.println(dis.readUTF());
dis.close();
s1.close();
}catch(ConnectExceptionconnExc){
System.err.println("服务器连接失败!
");
}catch(IOExceptione){
}
}
}
案例:
2203URL提取及应用举例
案例文件:
URLParser.java
目标:
在Java应用程序中实现网络数据传输和处理
代码:
/*范例名称:
URL提取及应用举例
*源文件名称:
URLParser.java
*描述:
通过一个URL入口,读出该页上的所有超连接
*要点:
*1.URL/URLConnection类及相关方法的使用
*2.Collection/ArrayList/Iterator/StringTokenizer类
*3.注释的使用
*4.系统属性的使用
*用法:
javaURLParser
*如果使用了代理服务器,则添加相应的系统属性:
*java-Dhttp.proxyHost=-Dhttp.proxyPort=URLParser
*@authorbily
*@versionv1.0
*/
importjava.io.IOException;
importjava.io.BufferedReader;
importjava.io.InputStreamReader;
importjava.util.Collection;
importjava.util.ArrayList;
importjava.util.Iterator;
importjava.util.StringTokenizer;
import.URL;
import.URLConnection;
import.MalformedURLException;
publicclassURLParser
{
//判断一段字串中是否含有子串"http"(超连接)
privatebooleanhasMatch(Stringtoken)
{
returntoken.indexOf("http:
")!
=-1;
}
/**
*从含有"http"子串的字符串中提取完整的URL
*/
privateStringtrimURL(Stringurl1)
{
StringtempStr=null;
intbeginIndex=url1.indexOf("http");
intendIndex=url1.length();
tempStr=url1.substring(beginIndex,endIndex);
endIndex=tempStr.indexOf('"');
if(endIndex==-1)
endIndex=tempStr.length();
returntempStr.substring(0,endIndex);
}
/**
*遍历输入的页面里的内容,以找出url
*@paramurlString输入的URL
*@returnurlsArrayList对象,其中包含已提取出的全部URL信息
*/
publicCollectionsearchURL(StringurlString)
{
URLurl2=null;
URLConnectionconn=null;
StringnextLine=null;
StringTokenizertokenizer=null;
CollectionurlCollection=newArrayList();
try
{
url2=newURL(urlString);
conn=url2.openConnection();
conn.setDoOutput(true);
conn.connect();
BufferedReaderReader1=newBufferedReader(newInputStreamReader(conn.getInputStream()));
while((nextLine=Reader1.readLine())!
=null)
{
tokenizer=newStringTokenizer(nextLine);
while(tokenizer.hasMoreTokens())
{
StringurlToken=tokenizer.nextToken();
if(hasMatch(urlToken))
urlCollection.add(trimURL(urlToken));
}
}
}
catch(MalformedURLExceptionex)
{
ex.printStackTrace();
}
catch(IOExceptionex)
{
ex.printStackTrace();
}
returnurlCollection;
}
/**
*主方法,需要一个命令行参数--要处理的URL
*/
publicstaticvoidmain(Stringargs[])
{
if(args.length!
=1)
{
System.out.println("用法:
javaURLParser");
System.exit(-1);
}
Stringurl3=args[0];
System.out.println("Searchingwebsite:
"+url3);
URLParserexample=newURLParser();
CollectionurlCollection=example.searchURL(url3);
Iteratoriter=urlCollection.iterator();
while(iter.hasNext())
{
System.out.println(iter.next());
}
}
}
案例:
2204聊天室程序
案例文件:
CreateTemp.java
目标:
ChatServer.java/ChatClient.java
代码:
/*范例名称:
聊天室程序
*源文件名称:
ChatClient.java/ChatServer.java
*要点:
*1.JavaSocket编程
*2.多线程编程
*3.程序体系结构及设计思想
*/
//源程序ChatServer.java
importjava.io.*;
import.*;
importjava.awt.*;
importjava.awt.event.*;
importjava.util.Vector;
publicclassChatServerextendsFrameimplementsWindowListener
{
TextAreadisplay;
intnum=1;
intport;
ServerSocketserver;
BufferedReaderinput;
BufferedWriteroutput;
VectormsgV;
/*
*构造方法完成初始化工作
*/
publicChatServer(intport1)
{
super("ChatServer,Running...");
display=newTextArea(200,300);
this.add("Center",display);
addWindowListener(this);
setSize(300,400);
show();
this.port=port1;
msgV=newVector(10);
}
/**
*关闭窗口事件
*1.显示正在关闭chatserver
*2.在消息队列msgV中加入"shutdown"字符串
*3.线程睡眠5001ms
*/
publicvoidwindowClosing(WindowEvente)
{
display.append("Serverisnowshuttingdown...\n");
display.append("InformingtheChatters...\n");
display.append("PleaseWait...");
msgV.add("shutdown");
try{Thread.sleep(5000);}
catch(Exceptione2){}
dispose();
System.exit(0);
}
publicvoidwindowOpened(WindowEvente)
{
}
publicvoidwindowActivated(WindowEvente)
{
}
publicvoidwindowClosed(WindowEvente)
{
}
publicvoidwindowDeactivated(WindowEvente)
{
}
publicvoidwindowDeiconified(WindowEvente)
{
}
publicvoidwindowIconified(WindowEvente)
{
}
publicvoidrun()
{
try
{
server=newServerSocket(port,3);
display.append("ChatServerisnowrunning!
\n");
while(true)
{
SocketclientSocket=server.accept();
clientConnectionconn=newclientConnection(clientSocket,num,display,msgV);
display.append("No"+(num++)+"chatmate\n");
}
}
catch(IOExceptione)
{
e.printStackTrace();
}
}
publicstaticvoidmain(Stringargs[])
{
ChatServerchatServer=newChatServer(7);
chatServer.run();
}
}
classclientConnectionextendsThread
{
Stringname;
SocketcSocket;
BufferedReaderinput;
PrintWriteroutput;
intnum;
TextAreadisplay;
VectormsgV;
publicclientConnection(SocketcSocket,intnum,TextAreadisplay,VectormsgV)
{
try{
input=newBufferedReader(newInputStreamReader(cSocket.getInputStream()));
output=newPrintWriter(cSocket.getOutputStream(),true);
this.name=input.readLine();
}
catch(IOExceptione)
{
e.printStackTrace();
}
this.cSocket=cSocket;
this.num=num;
this.display=display;
this.msgV=msgV;
this.start();
}
synchronizedpublicvoidrun()
{
Stringline;
try
{
while(true)
{
line=input.readLine();
if(line.equals("End"))
{
display.append("SystemMessage:
"+name+"isout!
\n");
break;
}
if(line.equals("PleaseSendALL"))
{
if(!
msgV.isEmpty())
{
intii=msgV.size();
output.println(ii);
for(intI=0;I{
output.println(msgV.get(I));
}
//output.println("end");
}
elseoutput.println("0");
}
else
{
line=name+"say:
"+line+"\n";
display.append(line);
msgV.add(line);
}
}
}
catch(IOExceptionex)
{
ex.printStackTrace();
}
finally
{
try
{
cSocket.close();
}
catch(IOExceptionex2)
{
ex2.printStackTrace();
}
}
}
}
//源程序ChatServer.java
importjava.io.*;
import.*;
importjava.awt.*;
importjava.awt.event.*;
publicclassChatClientextendsFrameimplementsRunnable,WindowListener,ActionListener
{
intnum=1;
booleanflag=true;
ThreadreceiveThread;
SocketsClient;
BufferedReaderinput;
PrintWriteroutput;
Stringname;
LabelhelloLabel=newLabel("Pleaseinput:
");
TextFieldsendText=newTextField(20);
ButtonsendButton=newButton("Send");
TextAreamessageText=newTextArea(100,20);
publicChatClient(Stringname,Stringservername)
{
super("Iam"+name);
try
{
sClient=newSocket(servername,7);
input=newBufferedReader(newInputStreamReader(sClient.getInputStream()));
output=newPrintWriter(sClient.getOutputStream(),true);
output.println(name);
}
catch(IOExceptione)
{
e.printStackTrace();
}
setBackground(newColor(220,220,255));
sendText.addActionListener(this);
sendButton.addActionListener(this);
sendButton.setSize(20,30);
Panelcp=newPanel();
cp.add(helloLabel);
cp.add(sendText);
cp.add(sendButton);
Panelsp=newPanel();
sp.add(messageText);
add("North",cp);
add("Center",messageText);
addWindowListener(this);
setSize(400,400);
show();
receiveThread=newThread(this);
receiveThread.start();
}
publicvoidwindowActivated(WindowEvente){
}
publicvoidwindowClosed(WindowEvente){
}
publicvoidwindowClosing(WindowEvente)
{
flag=false;
try{Thread.sleep(5000);}
catch(Exceptione2){}
output.println("End");
dispose();
System.exit(0);
}
publicvoidwindowDeactivated(WindowEvente){
}
publicvoidwindowDeico