JAVA22文档格式.docx

上传人:b****4 文档编号:16953035 上传时间:2022-11-27 格式:DOCX 页数:18 大小:19.27KB
下载 相关 举报
JAVA22文档格式.docx_第1页
第1页 / 共18页
JAVA22文档格式.docx_第2页
第2页 / 共18页
JAVA22文档格式.docx_第3页
第3页 / 共18页
JAVA22文档格式.docx_第4页
第4页 / 共18页
JAVA22文档格式.docx_第5页
第5页 / 共18页
点击查看更多>>
下载资源
资源描述

JAVA22文档格式.docx

《JAVA22文档格式.docx》由会员分享,可在线阅读,更多相关《JAVA22文档格式.docx(18页珍藏版)》请在冰豆网上搜索。

JAVA22文档格式.docx

TestServer.java/TestClient.java

掌握JavaSocket编程机制及其实现

简单的client/server程序

TestClient.java/TestServer.java

*1.JavaSocket编程步骤

*2.Socket/ServerSocket类用法

*3.通过Socket对象可以获取通信对方Socket的信息

//文件TestServer.java

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

publicclassTestClient{

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提取及应用举例

*描述:

通过一个URL入口,读出该页上的所有超连接

*1.URL/URLConnection类及相关方法的使用

*2.Collection/ArrayList/Iterator/StringTokenizer类

*3.注释的使用

*4.系统属性的使用

*用法:

javaURLParser

*如果使用了代理服务器,则添加相应的系统属性:

*java-Dhttp.proxyHost=<

hostname|IP>

-Dhttp.proxyPort=<

port>

URLParser<

url>

*@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;

/**

*从含有"

子串的字符串中提取完整的URL

privateStringtrimURL(Stringurl1)

StringtempStr=null;

intbeginIndex=url1.indexOf("

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())!

{

tokenizer=newStringTokenizer(nextLine);

while(tokenizer.hasMoreTokens())

{

StringurlToken=tokenizer.nextToken();

if(hasMatch(urlToken))

urlCollection.add(trimURL(urlToken));

}

catch(MalformedURLExceptionex)

ex.printStackTrace();

catch(IOExceptionex)

returnurlCollection;

*主方法,需要一个命令行参数--要处理的URL

publicstaticvoidmain(Stringargs[])

if(args.length!

=1)

用法:

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.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"

InformingtheChatters...\n"

PleaseWait..."

msgV.add("

try{Thread.sleep(5000);

catch(Exceptione2){}

dispose();

System.exit(0);

publicvoidwindowOpened(WindowEvente)

publicvoidwindowActivated(WindowEvente)

publicvoidwindowClosed(WindowEvente)

publicvoidwindowDeactivated(WindowEvente)

publicvoidwindowDeiconified(WindowEvente)

publicvoidwindowIconified(WindowEvente)

publicvoidrun()

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

ChatServerchatServer=newChatServer(7);

chatServer.run();

classclientConnectionextendsThread

Stringname;

SocketcSocket;

PrintWriteroutput;

intnum;

publicclientConnection(SocketcSocket,intnum,TextAreadisplay,VectormsgV)

input=newBufferedReader(newInputStreamReader(cSocket.getInputStream()));

output=newPrintWriter(cSocket.getOutputStream(),true);

this.name=input.readLine();

this.cSocket=cSocket;

this.num=num;

this.display=display;

this.msgV=msgV;

this.start();

synchronizedpublicvoidrun()

Stringline;

while(true)

line=input.readLine();

if(line.equals("

End"

))

{

display.append("

SystemMessage:

"

+name+"

isout!

break;

}

if(line.equals("

PleaseSendALL"

if(!

msgV.isEmpty())

{

intii=msgV.size();

output.println(ii);

for(intI=0;

I<

msgV.size();

I++)

output.println(msgV.get(I));

}

//output.println("

end"

elseoutput.println("

0"

}

else

line=name+"

say:

+line+"

;

display.append(line);

msgV.add(line);

finally

try

cSocket.close();

catch(IOExceptionex2)

ex2.printStackTrace();

}

publicclassChatClientextendsFrameimplementsRunnable,WindowListener,ActionListener

booleanflag=true;

ThreadreceiveThread;

SocketsClient;

LabelhelloLabel=newLabel("

Pleaseinput:

TextFieldsendText=newTextField(20);

ButtonsendButton=newButton("

Send"

TextAreamessageText=newTextArea(100,20);

publicChatClient(Stringname,Stringservername)

Iam"

+name);

sClient=newSocket(servername,7);

input=newBufferedReader(newInputStreamReader(sClient.getInputStream()));

output=newPrintWriter(sClient.getOutputStream(),true);

output.println(name);

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);

messageText);

addWindowListener(this);

setSize(400,400);

show();

receiveThread=newThread(this);

receiveThread.start();

publicvoidwindowActivated(WindowEvente){

publicvoidwindowClosed(WindowEvente){

flag=false;

output.println("

publicvoidwindowDeactivated(WindowEvente){

publicvoidwindowDeico

展开阅读全文
相关资源
猜你喜欢
相关搜索

当前位置:首页 > 农林牧渔 > 林学

copyright@ 2008-2022 冰豆网网站版权所有

经营许可证编号:鄂ICP备2022015515号-1