資源描述:
《java網(wǎng)絡(luò)編程代碼》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在行業(yè)資料-天天文庫。
1、例10-1Test.javaimportjava.net.*;importjava.io.*;importjava.util.Date;classTest{publicstaticvoidmain(Stringargs[])throwsException{intc;URLhp=newURL("http://www.whsvc.com.cn/");URLConnectionhpCon=hp.openConnection();System.out.println("Date:"+newDate(hpCon.getDate()));Sy
2、stem.out.println("Content-Type:"+hpCon.getContentType());System.out.println("Expires:"+hpCon.getExpiration());System.out.println("Last-Modified:"+newDate(hpCon.getLastModified()));intlen=hpCon.getContentLength();System.out.println("Content-Length:"+len);if(len>0){Syst
3、em.out.println("===Content===");InputStreaminput=hpCon.getInputStream();inti=len;while(((c=input.read())!=-1)&&(--i>0)){System.out.print((char)c);}input.close();}else{System.out.println("NoContentAvailable");}}}例10-2Client.javaimportjava.io.*;importjava.net.*;publiccl
4、assClient{publicstaticvoidmain(Stringargs[]){Strings=null;Socketsocket;DataInputStreamin=null;DataOutputStreamout=null;try{socket=newSocket("localhost",4331);in=newDataInputStream(socket.getInputStream());out=newDataOutputStream(socket.getOutputStream());out.writeUTF(
5、"Hello!It'sClient");while(true){s=in.readUTF();out.writeUTF(":"+Math.random());System.out.println("Clientget:"+s);Thread.sleep(2000);}}catch(IOExceptione){System.out.println("can'tconnect");}catch(InterruptedExceptione){}}}例10-3Server.javaimportjava.io.*;importjava.ne
6、t.*;publicclassServer{publicstaticvoidmain(Stringargs[]){ServerSocketserver=null;Socketsocket=null;Strings=null;DataOutputStreamout=null;DataInputStreamin=null;try{server=newServerSocket(4331);}catch(IOExceptione1){System.out.println("ERROR:"+e1);}try{socket=server.ac
7、cept();in=newDataInputStream(socket.getInputStream());out=newDataOutputStream(socket.getOutputStream());while(true){s=in.readUTF();out.writeUTF("It'sServer:");out.writeUTF("Clientsends:"+s);System.out.println("Servergets:"+s);Thread.sleep(2000);}}catch(IOExceptione){S
8、ystem.out.println(""+e);}catch(InterruptedExceptione){}}}例10-4WriteServer.javaimportjava.net.*;classWriteServer{publicstatic