版權(quán)說明:本文檔由用戶提供并上傳,收益歸屬內(nèi)容提供方,若內(nèi)容存在侵權(quán),請(qǐng)進(jìn)行舉報(bào)或認(rèn)領(lǐng)
文檔簡(jiǎn)介
9章工具類與算語(yǔ)言基礎(chǔ)類ObjectObject類是類庫(kù)中所有類的父類。有如下方法protectedObjectclone()生成當(dāng)前對(duì)象的一個(gè)拷貝,并返回這個(gè)對(duì)象publicbooleanequals(Objectobj) 同,是則返回truepublicfinalClassgetClass()獲取當(dāng)前對(duì)象所屬的類信息,Class對(duì)象protectedvoidfinalize() publicStringtoString() 數(shù)據(jù)類型數(shù)據(jù)類型類與基本數(shù)據(jù)類型密切相關(guān)。下面介紹Interger類構(gòu)造函數(shù)publicInteger(itnvalue)publics)可以分別利用一個(gè)基本數(shù)據(jù)類型int的量和一個(gè)字符串對(duì)象來(lái)生成一個(gè)Integer對(duì)象數(shù)據(jù)類型轉(zhuǎn)換方法分別將當(dāng)前對(duì)象所對(duì)應(yīng)的int量轉(zhuǎn)換成publicdoubledoubleValue()publicintintValue()publiclong字符串與int量相互轉(zhuǎn)化的方publicStringpublicstaticintparseInt(Strings)publicstaticIntegervalueOf(Strings)MathMath類的方法都是static的。publicfinalstaticdoubleE;數(shù)學(xué)常量epublicfinalstaticdoblePI;圓周率常publicstaticdoubleabs(doublea); publcistaticdoubleacos(doublea); publicstaticdoubleexp(doublea); //e的參數(shù)次冪publicstaticdoublefloor(doublea) publicstaticdoubleIEEEremainder(doublef1,double//求publicstaticdoublelog(double //自然對(duì)publicstaticdoublemax(doublea,doubleb); publicstaticfloatmain(floatafloatb) //最小值publicstaticdoublepow(doublea,doubleb) publicstaticdoublerandom() //01(不含)之間的publicstaticdoublerint(doublea) publicstaticdoublesqrt(doublea) SystemSystem類的屬性有三個(gè)標(biāo)準(zhǔn)輸入標(biāo)準(zhǔn)輸出和標(biāo)準(zhǔn)錯(cuò)誤輸PublicstaticPrintStreamerr;PublicstaticImputStreamin;PublicstaticPrintStream數(shù)(1) 創(chuàng)建數(shù)組空數(shù)組名=new類型[個(gè)數(shù)]intMy[]=newint[10];D200[]My=new如果是基本元素,則可省new并可同時(shí)給出初值intMy[]=初始要注意的問題有數(shù)組元素的下標(biāo)從0開始,至數(shù)組元素個(gè)數(shù)減1為所有數(shù)組元素有一個(gè)屬性length,表示數(shù)組元素的Java系統(tǒng)能自動(dòng)檢查是否有數(shù)組下標(biāo)越界的情classpublicclassArraySize//Mainpublicstaticvoidmain(String[]args){Weeble[]a; Weeble[]b=newWeeble[5]; Weeble[]c=newWeeble[4];for(inti=0;i<c.length;i++) c[i]=newWeeble(); a=newWeeble[]{newWeeble(),new 并動(dòng)態(tài)初始System.out.println("a.length="+a.length);System.out.println("b.length="+b.length);for(inti=0;i<b.length;i++)System.out.println("b["+i+"]"+b[i]);System.out.println("c.length="+c.length);System.out.println("d.length="+d.length);a=d;System.out.println("a.length="+int[]int[]f=newint[5];int[]g=newfor(inti=0;i<g.length;i++)g[i]=i*i;int[]h=//System.out.println("e.length="+e.length);System.out.println("f.length="+f.length);for(inti=0;i<f.length;i++)System.out.println("f["+i+"]="+f[i]);System.out.println("g.length="+g.length);System.out.println("h.length="+h.length);e=h;System.out.println("e.length="+e.length);e=newint[]{1,2};System.out.println("e.length="+e.length);}}向需要將不同類的對(duì)象組合成一個(gè)數(shù)據(jù)序需要做頻繁的對(duì)象序列中元素的插入和刪經(jīng)常需要定位序列中的對(duì)象或其他查找操在不同的類之間傳遞大量的數(shù)它的局限性是對(duì)象不能是簡(jiǎn)單類型創(chuàng)建向量類的對(duì)象:publicVector(intinitCapacity,intinitCapacity表示剛創(chuàng)建時(shí)Vector序列包含的元素?cái)?shù)capacityIncrement表示如果Vector序列中加元素,向向量序列中加元addElement(Object ement(Objectobj,int修改和刪 ementAt(Objectobj,intindex)removeElement(Objectobj)removeElementAt(intindex)查elementAt(intindex)contains(ObjectlastIndexOf(Objectobj,inta=a=字符字符串常量:StringString建一個(gè)無(wú)名的String類型對(duì)象。創(chuàng)建字符串常量String對(duì)String(Stringvalue)String(StringBufferbuffer)String(charvalue[])字符串常的操startsWith(Stringprefix)endsWith(Stringsuffix)字符串中單個(gè)字符的查indexOf(intindexOf(intch,int字符串中子串的查indexOf(Stringstr)indexOf(Stringstr,intfromIndex)lastIndexOf(Stringstr)lastIndexOf(Stringstr,int比較兩個(gè)字符compareTo(StringanotherString)equals(ObjectanObject)equalsIgnoreCase(StringanotherString)連接字符子concat(StringStringBuffer創(chuàng)建字符串變publicpublicStringBuffer(intlength)publicStringBuffer(Stringstr);publicStringBufferappend(Object)publicStringBufferinsert(int,Object)publicvoidsetCharAt(int,char)字符串的賦值和加=+遞遞歸的基本思想是自己調(diào)用自己參見如下的數(shù)列程 程序源代 說importjava.applet.Applet;importjava.awt.*;import {
Labelprompt=newLabel("ImportLength(LessthanTextFieldinput=newString[msg=new //創(chuàng)建長(zhǎng)度50的字符串?dāng)?shù)組msg t=0; t=publicvoid{for(inti=0;i<50;i++)msg[i]="";}publicvoidpaint(Graphicsg{for(inti=0;i< t+ t+1;i++)g.drawString(msg[i],10,40+15*i);}publicvoidactionPerformed(ActionEvent{if(e.getSource(){t=t={}}}longFibonacci(int{longt t+ t]=Blanks( t)+"Fibonacci("+n+"):";{t t-1)+"Return"+n;returnn;}{歸計(jì)
temp=Fibonacci(n-1)+Fibonacci(n- t t-1)+"Return"+temp;return}}StringBlanks(intstepIn,int{Stringblank=for(inti=0;i<(stepIn-stepBack);i++)blank=blank+"";return}}了解以下各種排序和查找方法的基本思想冒泡排選擇排插入排桶排順序查對(duì)分查鏈class{privateintm_Data;privateNodem_Next;Node(int{m_Data=data;m_Next=null;}Node(intdata,Node{m_Data=data;m_Next=}voidsetData(int{m_Data=}int{return}voidsetNext(Node{m_Next=}Node{return}}class{Node{m_FirstNode=}LinkList(int{m_FirstNode=new}String{Nodenext=m_FirstNode;Strings="";while(next!={s=s+next.getData()+";";next=next.getNext();}return}voidinsertAtBegin(int{if(m_FirstNode==null)m_FirstNode=newNode(data);m_FirstNode=new}voidinsertAfterId(intdata,int{Nodenext=m_FirstNode;if(next==null)m_FirstNode=newNode(data);{while(next.getNext()!=null&&next.getData()!=id)next.setNext(newNode(data,}}booleanremoveAtId(int{Nodeahead=m_FirstNode;Nodefollow=ahead;returnelse{m_FirstNode=m_FirstNode.getNext();returntrue;}{ahead=ahead.getNext();{{returntrue;}follow=ahead=}return}}void{m_FirstNode=}}publicclassUseLinkList//Mainpublicstaticvoidmain(String[]{LinkListlist=newLinkList(-1);for(inti=0;i<10;i++){}System.out.println("Notexist");}}輸出10過異常處理錯(cuò)異常與異常異常(Exception)和異常類是面向?qū)ο笠?guī)范的一部分異常類結(jié)構(gòu)與組所有Java異常類都是系統(tǒng)類庫(kù)中的Exception類的子java.lang包中的類Throwable類派生了兩個(gè)子類:Exception(應(yīng)用程序用)和Error(系統(tǒng)保留Exception的構(gòu)造函數(shù)有PublicPublicException(Strings提供錯(cuò)誤描常用方法有publicString //返回錯(cuò)誤描publicvoidprintStackTrace(); 系統(tǒng)定義的運(yùn)行異Exception有許多子類,每個(gè)子類代表一種特定的運(yùn)行時(shí)錯(cuò)用戶自定義的異創(chuàng)建用戶自定義異常時(shí),一般需要完成如下的工作一個(gè)新的異常類,父類為ExceptionclassEmptyQueueExceptionextendspublicStringtoString()classEmptyQueueExceptionextends{QueuePublicEmptyQueueException(Queue{super(“EmptyQueue”);sourceQueue=q;}publicString{}}10-1classSimpleExceptionextendsException{}publicclassSimpleExceptionDemo{publicvoidf()throws thrownew}//Mainpublicstaticvoidmain(String[]args){ try{}catch(SimpleExceptione){}}}10-classMyExceptionextendsException{publicMyException(){}publicMyException(Stringmsg){}}publicclassFullConstructorspublicstaticvoidf()throwsMyException{System.out.println("ThrowingMyExceptionfromf()");thrownewMyException();}publicstaticvoidg()throwsMyException{System.out.println("ThowingMyExceptionformg()");thrownewMyException("Originatedin}//Mainpublicstaticvoidmain(String[]args){try{}catch(MyExceptione){}try}
catch(MyExceptione){}}}輸出atuntitled1.MyException:Originateding()atuntitled1.FullConstructors.g(FullConstructors.java:20)atuntitled1.FullConstructors.main(FullConstructors.java:31)ThrowingMyExceptionfromf()ThowingMyExceptionform10-classMyException2extendsException{publicMyException2(){}publicMyException2(Stringmsg){}publicMyException2(Stringmsg,intx){i=}publicintval(){returni;}privateinti;}publicclassExtraFeaturespublicstaticvoidf()throwsMyException2{System.out.println("ThrowingMyException2fromf()");thrownewMyException2();}publicstaticvoidg()throwsMyException2{System.out.println("ThowingMyException2formg()");thrownewMyException2("Originateding()");}publicstaticvoidh()throwsMyException2{System.out.println("ThowingMyException2formh()");thrownewMyException2("Originatedinh()",47);}//Mainpublicstaticvoidmain(String[]args){try{}catch(MyException2e){}try}
catch(MyException2e){}try}catch(MyException2e){System.err.println("e.val()="+e.val());}}}輸出atatuntitled1.ExtraFeatures.main(ExtraFeatures.java:36)untitled1.MyException2:Originateding()atatuntitled1.ExtraFeatures.main(ExtraFeatures.java:42)untitled1.MyException2:Originatedinh()atatuntitled1.ExtraFeatures.main(ExtraFeatures.java:48)e.val()=47ThrowingMyException2fromf()ThowingMyException2formg()ThowingMyException2formh()拋出異Java程序在運(yùn)行時(shí)如果了一個(gè)可識(shí)別的錯(cuò)誤就會(huì)系統(tǒng)自動(dòng)拋出的異所有系統(tǒng)定義的運(yùn)行異常都可以由系統(tǒng)自動(dòng)拋出。如語(yǔ)句拋出的異用戶自定義的異常必須錯(cuò)助于throw語(yǔ)句來(lái)定義拋出intdequeue()throws{intifthrow(newEmptyQueueException(this));}必須注意以下兩個(gè)情況throw語(yǔ)句放if分支中,即滿足一定條件時(shí)拋出異含有throw語(yǔ)句的方法,應(yīng)該在方法頭中增加throws異常類名列異常的處捕捉異While{System.out.print(queue.dequeue()+“ //里可能會(huì)拋出異 }}catch(EmptyQueueException{}多異常的處catchtry后面,每個(gè)catch塊都有一個(gè)異常類捕捉所有異publicclassExceptionMethods//Mainpublicstaticvoidmain(String[]args){try{thrownewException("Here'smy}catch(Exceptione){ System.err.println("e.toString():"+e);}new}}輸出CaughtExceptione.getMessage():Here'smyExceptione.getLocalizedMessage():Here'smye.toString():java.lang.Exception:Here'smyExceptionjava.lang.Exception:Here'smyException重新拋出異publicclassRethrowingpublicstaticvoidf()throwsException{System.out.println("fromf()");thrownewException("ThowingExceptionform}publicstaticvoidg()throwsThrowable{}catch(Exception //如果這兩句修改則輸出為輸出//throw}}//Mainpublicstaticvoidmain(String[]args)throwsThrowable{try{}catch(Exceptione) }}}輸出g(),java.lang.Exception:ThowingExceptionformf()atuntitled1.Rethrowing.f(Rethrowing.java:9)atuntitled1.Rethrowing.g(Rethrowing.java:14)atCaughtinmain,e.printStackTrace()java.lang.Exception:ThowingExceptionformf()atuntitled1.Rethrowing.f(Rethrowing.java:9)atuntitled1.Rethrowing.g(Rethrowing.java:14)atuntitled1.Rethrowing.main(Rethrowing.java:26)fromf()Insideg(),e.printStackTrace()java.lang.Exception:Thowingformf()atuntitled1.Rethrowing.f(Rethrowing.java:9)atuntitled1.Rethrowing.g(Rethrowing.java:14)atuntitled1.Rethrowing.main(Rethrowing.java:26)Caughtinmain,e.printStackTrace()java.lang.Exception:Thowingformf()atatuntitled1.Rethrowing.main(Rethrowing.java:26)Originatingtheexceptioninf()因?yàn)閒illInStackTrace()的緣故,改變了異常的classOneExceptionextendspublicOneException(Strings)}classTwoExceptionextendsException{publicTwoException(Strings){super(s);}}publicclassRethrowNewpublicstaticvoidf()throwsOneException{System.out.println("Originatingtheexceptioninf()");thrownewOneException("thrownfromf()");}//Main try}catch(OneExceptione) thrownewTwoException("from}}}輸出Caughtinmain,e.printStackTrace()untitled1.OneException:thrownfromf()atuntitled1.TwoException:frommain()atuntitled1.RethrowNew.main(RethrowNew.java:28)Exceptioninthread"main"Originatingtheexceptioninf()最后一個(gè)只拋出,沒有截取的,回收器負(fù)責(zé)清Java標(biāo)準(zhǔn)異Throwable有兩類:Error和Exception.Error無(wú)需捕捉,代表編譯期錯(cuò)誤和系統(tǒng)錯(cuò)誤Exception代表可能從(1)Java標(biāo)準(zhǔn)程序庫(kù)內(nèi),(2)用戶函數(shù)執(zhí)行期發(fā)生的意外事RuntimeException可以一路傳遞直至finally進(jìn)行清無(wú)論是否拋出異常,finally子句都會(huì)被執(zhí)行classThreeExceptionextendsException{}publicclassFinallyWorks{staticintcount=//Mainpublicstaticvoidmain(String[]args){while(true){tryif(count++==0) thrownewThreeException();System.out.println("Noexception");}catch(ThreeExceptione){}System.err.println("Infinallyclause");if(count==2)break;}}}}InfinallyclauseInfinallyclauseNoexception不管有沒有異常,finally是一定要做異常遺classVeryImportantExceptionextendsException{publicStringtoString(){return"Averyimportant}}classHoHumExceptionextendsException{publicStringtoString(){return"Atrivial}}publicclassLostMessagevoidf()throwsthrownew}voiddispose()throwsHoHumException{thrownewHoHumException();}//Mainpublicstaticvoidmain(String[]args)throwsException{LostMessagelm=newLostMessage();}}}輸出Atrivialatuntitled1.LostMessage.dispose(LostMessage.java:22)atuntitled1.LostMessage.main(LostMessage.java:30)Exceptioninthread沒有出現(xiàn)VeryImportantException,第二個(gè)異常HoHumException在第一個(gè)異常處理之前拋11JavaI/O系Java輸入輸出類java的輸入輸出功能通過輸入輸出類庫(kù)java.io包實(shí)現(xiàn)Java.io中有一個(gè)類(File)專門用于文件系統(tǒng)交互BooleancanRead();BooleancanWrite();Booleanexitsts();StringgetAbsolutePath();BooleanisFile();BooleanisDirectory();Booleanlength();BooleancreateNewFile();Booleandelete();VoiddeleteOnExit();//程序運(yùn)行結(jié)束時(shí)刪除該文Boolean流的概流式輸入輸出的特點(diǎn)是:數(shù)據(jù)的獲取和發(fā)送是順序的數(shù)據(jù)可以是二進(jìn)制,字符,數(shù)字等輸入輸出流基本輸入輸出InputStream類是抽象類,具體對(duì)象是它的子類對(duì)象publicintread(以二進(jìn)制方式讀publicintread(byteb[]); publiclongskip(longn);//n個(gè)字節(jié)publicvoidmark(); publicvoidreset(); publicvoidclose(); OutputStream類是抽象類,具體對(duì)象是它的子類對(duì)主要方法有publicintwrite(intb);//將參b的低位字節(jié)寫入publicintwrite(byteb[]); //將參數(shù)b中的全部字publicvoidflush(); publicvoid //關(guān)閉幾種具體輸入輸出過濾 文件:FileInputStream,管道 FilterInputStream,和FilterOutputStream的子類: ReadByte(),readBoolean(),readShort(),…….WriteByte(),writeInt(),……標(biāo)準(zhǔn)輸入輸標(biāo)準(zhǔn)輸System.in.read()要注意try中,可接收異讀一個(gè)字節(jié)的數(shù)據(jù),返回16位值,高80,且只能如鍵盤緩沖區(qū)沒有值,則進(jìn)程掛起ch= //從鍵盤緩沖區(qū)讀入字節(jié)的數(shù)據(jù)}catch(IOExceptione)標(biāo)準(zhǔn)輸System.out.println(“Pressanykeytofinishtheprogram”);charrest=}catch(IOException程序?qū)嵗齣mportjava.io.*;publicclassInAndOut{publicstaticvoidmain(String{BufferedReaderin s=in.readLine();}catch(IOExceptionSystem.out.println("Youareenteredstring:"+}}文件的處理與隨Java程序的文件與管File類的對(duì)象表示一個(gè)磁盤文件或,其對(duì)象屬性中包含了文件或的相關(guān)信息,如名稱,長(zhǎng)度,所含文可以是絕對(duì),相對(duì),靜態(tài)屬性System.dirSep作File類的對(duì)構(gòu)造函數(shù)File(String 例如Filef1=newStrings=Filef2=newnewFile(Stringpath,String// 與名稱分開的方例如Filef3=File(“myProgram\Java”,File(Filedir,String例如Stringsdir=“myProgram”+System.dirSep+”Java”;Stringsfile=“FileIO.data”;FileFdir=newFileFfile=new publicbooleanexists() publicbooleanisFIle() //publicbooleanisDirectory() publicStringgetName() publicStringgetPath()//publiclonglength()publicbooleancanRead()publicbooleancanWrite()publicString[]list();publicbooleanequals(File文件 操publicbooleanrenameTo(FilenewFile)publicvoiddelete()publicboolean程序?qū)嵗齣mportpublicclassFileOperation//Mainpublicstaticvoidmain(Stringargs[]{try Stringsdir="e:\\temp";Stringsfile;FileFdir1=newFile(sdir);if(Fdir1.exists()&&Fdir1.isDirectory()){System.out.println("Thereisadirectory"++"for(inti=0;i<Fdir1.list().length;i++)FileFdir2=newFile("e:\\temp\\temp"); createanewdir:");for(inti=0;i<Fdir2.list().length;i++)} sfile=FileFfile=newFile(Fdir1,sfile);{System.out.println("File"+Ffile.getName()+"inPath"+Ffile.getPath()+"is"+Ffile.length()+"in}}catch(Exceptione){}}}文件輸入輸出FileInputStream利用文件名字符串或File對(duì)象創(chuàng)建輸入輸出流對(duì)FileInputStream(StringFileInputStream(File利用已File對(duì)象創(chuàng)建從該對(duì)象對(duì)應(yīng)的磁盤從文件輸入輸出流中讀寫數(shù)FileMyFile=new DataOutputStreamdout=newDataOutputStream(new程序?qū)嵗齣mportjava.io.*;publicclassMyFileIo{//Mainpublicstaticvoidmain(String[]args){charch;intFileMyPath=newFile("\\temp");FileMyFile1=newFile(MyPath,"crt.txt");try{ System.out.println("InputaStringfinishedwith#while((ch=(char)System.in.read())!='#')FileInputStreamfin=newFileInputStream(MyFile1);while((chi=fin.read())!=-1)}catch(FileNotFoundExceptione){}catch(IOExceptione){}}}程序?qū)ξ募碾SRandomAccessFile對(duì)象RandomAccessFile(StringnameStringmode);RandomAccessFile(Filef,Stringmode);FileBackMegFile=newFile(“BankFile.txt”); 對(duì)文件位置指針的操RandomAccessFile對(duì)象的文件位置指針位于文件每次讀寫操作后文件位置指針相應(yīng)后移讀寫的字longgetPointer()方法可得到當(dāng)前文件位置指針?biāo)趘oidseek(longpos)可移動(dòng)文件位置指針用longlength()可返回文件的字節(jié)長(zhǎng)度讀操實(shí)現(xiàn)DataInput接口,RandomAccessFile中的讀方法 readFloat(),readDouble(),readLine(),readUTF().寫操RandomAccessFile 程序?qū)嵗齣mportimportjava.awt.event.*;importjava.awt.*;publicclassTestFileDialogpublicstaticvoidmain(String[]args){newFileFrame();}}classFileFrameextendsFrameimplements{TextAreata;Buttonopen,quit;FileDialogfd;{super("Acquireanddisplaytext");ta=newTextArea(10,45);open=newButton("Open");quit=newButton("Close");setLayout(newFlowLayout());}publicvoidactionPerformed(ActionEvent{ { Filemyfile=newFile(fd.getDirectory(),fd.getFile()); {ta.append(raf.readLine()+}}catch(IOException{}} {}}}第12章網(wǎng)絡(luò)編基于連接的流式套接套接字(Socket)是TCP/IP協(xié)議的編程接口,通過提供的一組APITCP/IP協(xié)議InetAddressInetAddress類對(duì)象中包含了IP地址,主機(jī)名等的IP地址。程序?qū)嵗齣mportpublicclassMyIPAddresspublicstaticvoidmain(String[]args){try{if(args.length{ }}catch(UnknownHostExceptione)}}}Socket是基于連接的通信,在通信開始之前由通信雙方確認(rèn)并建立一條的虛擬連接通道,通信結(jié)束后SocketServerSocket創(chuàng)建一個(gè)ServerSocket對(duì)象就創(chuàng)建了一個(gè)服務(wù),創(chuàng)建了一個(gè)Socket對(duì)象就建立了一個(gè)ClientServer間的連ServerSocket類//提供服務(wù)的端為SocketLinkSocket=//Server等待直到捕捉到來(lái)自Client端的請(qǐng)并返回Socket對(duì)象LinkSocket,用于寫數(shù)據(jù)。//Socket類 puterName”,8000);//欲連接的主機(jī)地址,提供服務(wù)的端 創(chuàng)建Socket對(duì)象,向Server 端口請(qǐng)Socket中讀寫Server端通信Client創(chuàng)建Socket對(duì)象,向Server 端口請(qǐng)Socket中讀寫Server端通信Client ServerSock對(duì)象在 Socket中讀寫數(shù)據(jù)Client端通信接收ClientSocket建立連接Client端的服務(wù)Server關(guān)閉Socket,關(guān)閉關(guān)閉ServerSocket對(duì)象結(jié) 實(shí)現(xiàn)流式Socket通信的ClientServer端編程序?qū)嵗?/Server端程importjava.io.*;importjava.awt.*;import.*;importpublicclassMySocketServerpublicstaticvoidmain(String[]{ }}classServiceThreadextendsFrameimplements{ServerServiceFatherListener;SocketConnectedClient;ThreadConnectThread;PanelListenerPanel;TextAreaServerMeg;publicServiceThread(ServerServicesv,Socket{FatherListener=sv;ConnectedClient=s;ConnectThread=newThread(this);setTitle("AnswerClient");setLayout(newBorderLayout());ServerMeg=newTextArea(10,50);add("Center",ServerMeg); ClientAddress.toString()+"\n");}publicvoid{DataInputStreamin=newDataInputStream(new
econnecttoourStrings=in.readLine();{ServerMeg.append("ClientInputInfo:\n"+s);s=in.readLine();}}catch(Exceptione){}FatherListener.addMeg("Client"+"closed."+"\n");}}classServerServiceextends{ServerSocketpublicServerService(intPort,int{try m_sListener=newServerSocket(Port,Count);m_sListener=newServerSocket(Port);setTitle("ServerListener");this.addWindowListener(newWinAdpt());setLayout(newBorderLayout());
add("Center",ListenerMeg);{SocketConnected=m_sListener.accept(); ListenerMeg.append("Client"+"connected"+"from\n"+ClientAddress.toString()+".\n");}}}}
ServiceThreadMyST=newcatch(IOException}publicvoidaddMeg(String{}}classWinAdptextends{publicvoidwindowClosing(WindowEvent{}//Client端程序importjava.io.*;importjava.awt.*;import.*;importclassMyClientextendsFrameimplements{SocketClientSocket;PrintStreamos;DataInputStreamis;Strings;LabelMylabel=newLabel(" e");TextAreatextArea;ButtonMyButton=newpublicstaticvoidmain(String{newpublic{setTitle("ClientWindow");setLayout(newBorderLayout());this.addWindowListener(newWinAdptClient(this));textArea=newTextArea(20,50);add("Center",textArea);}publicvoid{ClientSocket=new s=is.readLine();}catch(Exception}publicvoidactionPerformed(ActionEvent{{}catch(Exception}}}classWinAdptClientextends{MyClientm_Parent;WinAdptClient(MyClientp){m_Parent=}publicvoidwindowClosing(WindowEvent{try}catch(Exception}}無(wú)連接的數(shù)據(jù)數(shù)據(jù)Socket又稱UDP套接字直接將信息打包傳向指DatagramPacketDatagramSocketDatagramPacket類:用于數(shù)PublicDatagramPacket(byteibuf[],int InetAddressiaddr,intiport)(I,目的地的端口)DatagramSocket類:用于實(shí)現(xiàn)數(shù)據(jù)報(bào)的發(fā)送和接收過PublicPublicDatagramSocket(int UDP的編程實(shí)數(shù)據(jù)報(bào)的發(fā)送過程DatagramPacket對(duì)提供要發(fā)送的數(shù)據(jù)數(shù)據(jù)報(bào)分組長(zhǎng)度發(fā)送目的機(jī)地址和目的端在指定的或可用的本機(jī)端口創(chuàng)建DatagramSocket對(duì)象DatagramSocket.send()數(shù)據(jù)報(bào)的接收過程DatagramPacket對(duì)象DatagramSocket對(duì)importjava.io.*;.*;publicclassUDPServerService//Mainpublicstaticvoidmain(String[]args){{System.out.println("Pleaseinputlocal}UDPServerThreadMyUDPServer=new}}classUDPServerThrea
溫馨提示
- 1. 本站所有資源如無(wú)特殊說明,都需要本地電腦安裝OFFICE2007和PDF閱讀器。圖紙軟件為CAD,CAXA,PROE,UG,SolidWorks等.壓縮文件請(qǐng)下載最新的WinRAR軟件解壓。
- 2. 本站的文檔不包含任何第三方提供的附件圖紙等,如果需要附件,請(qǐng)聯(lián)系上傳者。文件的所有權(quán)益歸上傳用戶所有。
- 3. 本站RAR壓縮包中若帶圖紙,網(wǎng)頁(yè)內(nèi)容里面會(huì)有圖紙預(yù)覽,若沒有圖紙預(yù)覽就沒有圖紙。
- 4. 未經(jīng)權(quán)益所有人同意不得將文件中的內(nèi)容挪作商業(yè)或盈利用途。
- 5. 人人文庫(kù)網(wǎng)僅提供信息存儲(chǔ)空間,僅對(duì)用戶上傳內(nèi)容的表現(xiàn)方式做保護(hù)處理,對(duì)用戶上傳分享的文檔內(nèi)容本身不做任何修改或編輯,并不能對(duì)任何下載內(nèi)容負(fù)責(zé)。
- 6. 下載文件中如有侵權(quán)或不適當(dāng)內(nèi)容,請(qǐng)與我們聯(lián)系,我們立即糾正。
- 7. 本站不保證下載資源的準(zhǔn)確性、安全性和完整性, 同時(shí)也不承擔(dān)用戶因使用這些下載資源對(duì)自己和他人造成任何形式的傷害或損失。
最新文檔
- 【正版授權(quán)】 ISO 21506:2024 EN Project,programme and portfolio management - Vocabulary
- 小學(xué)中隊(duì)隊(duì)干部競(jìng)選主題班會(huì)《我們是少先隊(duì)的小主人》
- 2022年三年級(jí)語(yǔ)文下冊(cè)第七單元主題閱讀+答題技巧(含答案、解析)部編版
- 2024年汕頭小型客運(yùn)從業(yè)資格證考試
- 2024年雙鴨山客運(yùn)資格證仿真考試題
- 2024年西安客運(yùn)從業(yè)資格證理論考試題庫(kù)
- 2024年石家莊客運(yùn)從業(yè)資格證的考題
- 吉首大學(xué)《國(guó)際市場(chǎng)營(yíng)銷》2021-2022學(xué)年第一學(xué)期期末試卷
- 《機(jī)械設(shè)計(jì)基礎(chǔ)》-試卷13
- 吉林藝術(shù)學(xué)院《舞蹈教育學(xué)》2021-2022學(xué)年第一學(xué)期期末試卷
- 店長(zhǎng)轉(zhuǎn)正考核(員工評(píng)價(jià))
- 9-2 《第三方過程評(píng)估淋蓄水檢查內(nèi)容》(指引)
- 鐵路企業(yè)高技能人才隊(duì)伍建設(shè)的對(duì)策與措施
- 亞馬遜品牌授權(quán)書(英文模板)
- 《現(xiàn)代漢語(yǔ)修辭》PPT課件(完整版)
- TTJCA 0007-2022 住宅室內(nèi)裝飾裝修工程施工驗(yàn)收規(guī)范
- 構(gòu)造柱工程施工技術(shù)交底
- 流體力學(xué)筆記整理
- 現(xiàn)代簡(jiǎn)約風(fēng)格發(fā)展趨勢(shì)
- 路緣石滑模施工工法
- 設(shè)備稼動(dòng)率如何計(jì)算
評(píng)論
0/150
提交評(píng)論