Lap Trinh Mang Voi Java

66
Lập trình mạng với Java

description

hj

Transcript of Lap Trinh Mang Voi Java

  • Lp trnh mng vi Java

  • Ni dungNgn ng Java cn bnLp v i tng trong JavaExceptionNhp / xut trong Java Lp trnh Socket Lp trnh RMI

  • Ngn ng JavaJava l ngn ng lp trnh hng i tng

    Mt chng trnh Java thng bt u bng mt khai bo lp (class); trong , c phng thc main l im bt u thc thi ca chng trnh:public static void main (String[] agrs)

    Java h tr cc cu trc iu khin:if-elseswitchforwhiledo-while

    Java cung cp ba cu lnh break,continue v return cho php chuyn iu khin t on lnh ny sang on khc.

  • Cch thi hnh 1 chng trnh Javajavac myProgram.javajava myProgram

  • Kiu d liubytecharbooleanshortintlongfloatdoubleArrayClassInterface

  • Chuyn i kiu d liu [1]float c = 34.89675f;int b = (int)c + 10;c = b; Trong qu trnh chuyn i kiu d liu, mt kiu d liu s c chuyn i sang mt kiu d liu khc.

    V d

  • Chuyn i kiu d liu [2]C hai cch chuyn i kiu d liu: t ng chuyn i kiu d liu v php p kiu d liu.Khi d liu ,vi mt kiu d liu cho trc, c gn cho mt bin c kiu d liu khc, qu trnh chuyn i kiu d liu t ng thc hin nu tha cc iu kin sau:Hai kiu d liu tng thch nhauKiu d liu ch ln hn kiu d liu ngunp kiu d liu l s chuyn i d liu tng minh. N c th lm mt thng tin

  • Cc lut m rng kiu d liu Tt c cc gi tr kiu byte and short c m rng thnh kiu int

    Nu mt ton hng c kiu long, kiu d liu ca ton biu thc s c m rng thnh kiu long

    Nu mt ton hng c kiu float, kiu d liu ca ton biu thc s c m rng thnh kiu float

    Nu mt ton hng c kiu double, kiu d liu ca ton biu thc s c m rng thnh kiu double

  • BINBin trong Java c 3 loi: static variable, instance varible v local variable.static/instance variable: c th c s dng m khng cn khi to gi tr (c t ng gn gi tr mc nh).local varible: bt buc phi khi to gi tr trc khi s dng. Nu khng s to ra li khi bin dch.class test{ static int a; public static void main(String[] args){int b;System.out.println(a);System.out.println(b); }}

  • BinC ba thnh phn trong mt khai bo bin:Kiu d liuTn binGi tr khi gn ( ty )

    C phpkiu_d_liu tn_bin [= gi_tr];V ddouble d = 5.5;

  • MngC ba cch khai bo mngkiu_d_liu tn_bin []; kiu_d_liu tn_bin []=new kiu_d_liu [s_pt]; kiu_d_liu tn_bin [] = {gtr1, gtr2,., gtrN}; V dint a[];int a[] = new int [10];float af[] = {5.3, 7.6, 8.9, 3.0};

  • Cc cu trc iu khinCu trc r nhnhif-elseswitch-case Cu trc lpwhile do-while for

  • Tham s ca chng trnhXt on CTclass ArgsTest { public static void main(String[] args) {for(int i=0;i
  • if-elseif (biu_thc_iu_kin){khi_lnh_1;}else{khi_lnh_2;}

  • switch-caseswitch (biu_thc){case gi_tr_1:khi_lnh_1;break;case gi_tr_2:khi_lnh_2;break;...default:khi lnh_n;}

  • forfor (nhm_lnh_khi_to; bthc_iu_kin; nhm_lnh_tng_gim_gi_tr){khi_lnh_lp;}

  • whilewhile (biu_thc_iu_kin){khi_lnh_lp;}

  • do-whiledo{khi_lnh_lp;} while (condition);

  • Lp v i tngLp nh ngha mt kiu d liu mii tng thuc mt lp trong Java lun c cp pht ng, s dng t kha newBin c kiu d liu l mt lp c th tham chiu n mt i tng thuc lpV dMy_Class object;object = new My_Class( );

  • Phng thcKhai bo access_specifier modifier kiu_d_liu tn_phng_thc (danh_sch_tham_s){} access_specifier: public, protected, none (default), privatemodifier: static, final, abstract

  • Phng thc [2]Nguyn tc truyn tham s vo phng thc:Kiu d liu l kiu c s: truyn bng tham s trKiu d liu l kiu tham chiu: truyn bng tham chiu.

    Phng thc trong lp c th overloading: nhiu phng thc c cng tn nhng khc danh sch tham s.

    Cc phng thc overriding l cc phng thc ging nhau nhng c khai bo trong cc lp khc nhau c quan h k tha.

  • Phng thc [3]void f ( int i ) { }void g ( Object o ) { }________int k=5;f ( 5 );f ( k ); // truyn tham tr________ g ( obj ); // truyn tham chiu

  • Phng thc khi toC cng tn vi tn lp v khng c kiu tr v

    c t ng gi thc hin ngay khi i tng thuc lp c to ra.

    C hai loi phng thc khi to: c tham s v khng tham s (phng thc khi to mc nh). Ty thuc vo cch khi to i tng m phng thc khi to tng ng c gi thc hin.

  • LP TRU TNGLp tru tng l lp ch c th dng khai bo bin. khai bo lp tru tng dng t kha abstract: abstract class Number { . . . } mt lp tru tng c th cha cc phng thc tru tng. Lp tru tng khng th final.

  • Interfacesinterface l tp hp cc khai bo hm v cc hng. lp ci t interface c ngha l lp nh ngha cc hm c khai bo trong interface. interface khng tham gia vo cu trc phn cp lp. 2 lp khng lin quan c th ci t cng 1 interface.

  • Khai bo InterfaceC php: interface{}thn interface cha cc khai bo hm. cc hm ny mc nh l public v abstract.interface c th cha khai bo bin. cc bin ny mc nh l l public, static, v final.

  • PackagesPackagescu trc th mc cha cc lp v interfacec ch gi tn cc lp/interface. to package thm lnh sau vo dng u tin ca compilation unitpackage ; s dng lp/interface trong package, s dng lnh import.

  • K tha lp[1]Lp dn xut k tha tp cc thuc tnh c khai bo trong lp c s.

    Lnh gi thc thi phng thc khi to ca lp c s phi l cu lnh u tin trong hm khi to ca lp dn xut.

    Nu trong phng thc khi to ca lp dn xut khng gi (tng minh) phng thc khi to ca lp c s th phng thc khi to mc nh ca lp c s lun c t ng gi thc hin.

    Phm vi truy cp ca cc phng thc trong lp dn xut phi bng hoc rng hn trong lp c s.

  • K tha lp [2]class A {A () {}A (int i) {}} // end class A

    class B extends A {B () {[super();]...}B (int i, int j) {super(i);...}B (int k) {...}} // end class B

  • K tha lp [3]class A {void f () { ... }public void g (int i) { ... }} // end class A

    class B extends A {void f () {... } //[none],protected,public___ void g (int i) { ... } // public only} // end class B

  • T kha superT kha super c s dng gi thc hin phng thc khi to ca lp c ssuper(); // gi constructor ca lp c s

    T kha super c th c s dng tham chiu n cc thuc tnh hoc gi thc hin cc phng thc ca lp c s.super.f( ); // gi phng thc f() ca lp c s

  • K tha Interface khai bo 1 lp ci t interface dng t kha implements. 1 lp c th ci t cng 1 lc nhiu interface. Interface ch cha khai bo hm. 1 lp ci dt interface phi ci t tt c cc khai bo hm. Cc hm trong interface phi c ci t vi t kha public

  • T kha static [1]C th t trc mt khai bo thuc tnh hay phng thcstatic int i;public static void f ( ) { }Thuc tnh static l thuc tnh duy nht c chia x bi tt c cc i tng thuc lp.Phng thc static ch truy xut c cc thuc tnh static.Cc thnh vin static c th c truy xut thng qua tn lp

  • Wrapper ClassesNm trong gi java.langng gi cc kiu d liu c s di dng cc lp.c s dng khi cn dng mt i tng biu din mt kiu c s.Cc wrapper class dng cho kiu s: Double, Float, Byte, Short, Integer v LongLp Character l wrapper class dng cho kiu d liu char.Lp Boolean l wrapper class dng cho kiu d liu boolean.

  • Lp String [1]Trong Java, mt chui k t l mt i tng thuc lp String.Lp String cung cp cc phng thc thao tc trn cc chui k tint length(): xc nh chiu di ca mt String.int indexOf(String): tm mt chui con trong mt chui.String toLowerCase(): chuyn i thnh chui thng.String toUpperCase(): chuyn i thnh chui hoa.

  • Lp String [2]String s1= abc;int len= s1.length();// len = 3

    int pos= s1.indexOf(a);// pos=0pos= s1.indexOf(g); //pos=-1

    String s2= s1.toUpperCase(); // s2= ABCString s3= s2.toLowerCase(); // s3= abc

  • Lp String [3]Mi khi thc hin thay i trn mt String, mt i tng String mi s c to nn vi nhng thay i trong . Chui k t ban u khng thay i.

    Ton t == v != cng c p dng trn cc i tng thuc lp String.

    so snh ni dung ca hai String, s dng phng thc equals(String)

    V dString str1= new String (abc);String str2= new String (abc);[str1 == str2;str1.equals(str2); ]

  • ExceptionCc exception trong Java c th c x l trong chng trnh bng cc t kha: try, catch, throw, throws, v finally.try {Khi_lnh_cn_thc_hin;} catch ( ) {Khi_lnh_x_l_exception;} catch ( ) {...} finally {Khi_lnh_kt_thc;}

  • Cc lp Exception

  • X l exception [1]C hai cch x l exception trong Java:X l exception trong khi lnh catch.Khai bo phng thc nm ra exception tng ng khng x l exception.void f() throws IOException { }

  • X l exception [2]try { byte[] buffer= new byte[128];int len=System.in.read(buffer);System.out.println(new String(buffer, 0, len) );} catch ( IOException e ) { e.printStackTrace();} finally { System.out.println(Finally.);}

  • Nhp / xut d liuS dng cc lung nhp xut trong gi java.io

    C hai loi lung nhp/xut trong Java:Cc lung d liu kiu byte:X l d liu nhp/xut theo tng byte.Hai lp c s l: InputStream v OutputStreamCc lung d liu kiu k t:X l d liu theo tng k tHai lp c s l: Reader v Writer

  • Cc lp v interfaceObjectFileFileDescriptorRandomAccessFileDataInputDataOutputDataInputStreamBufferedInputStreamLineNumberInputStreamPushBackInputStreamFilterInputStreamInputStreamByteArrayInputStreamFileInputStreamOutputStreamFileOutputStreamFilterOutputStreamByteArrayOutputStreamBufferedOutputStreamDataOutputStreamPrintStream

  • c d liu t Console[1]S dng i tng System.in

    try { byte data[]= new byte[128]; System.out.print(Enter a string: ); int len= System.in.read(data); String str= new String(data, 0, len); System.out.println(str);} catch (IOException ex) { ex.printStackTrace();}

  • c d liu t Console[2]S dng lp i tng BufferedReader

    try { BufferedReader br= new BufferedReader( new InputStreamReader(System.in)); System.out.print(Enter a string: ); String str= br.readLine(); System.out.println(str);} catch (IOException ex) { ex.printStackTrace();}

  • c d liu t tp tinc d liu, s dng lp i tng FileInputStream

    FileInputStream fis= new FileInputStream();byte buffer[]= new byte[128];int len=0;while (len != -1) {len= fis.read(buffer);}fis.close();

  • Ghi d liu ra tp tinXut d liu, s dng lp i tng FileOutputStream

    FileOutputStream fos= new FileOutputStream();String str= hello;fos.write(str.getBytes());fos.close();

  • Lp trnh SocketCc my tnh trn mng Internet trao i thng tin s dng b giao thc TCP/IP.Transport: TCP , UDPNetwork: IP

  • Internet AddressLp InetAddress ng gi a ch IP v tn min ca mt my tnh.

    Lp InetAddress khng c hm khi to. to ra i tng thuc lp ny, s dng cc phng thc: getLocalHost(), getByName(String), getAllByName(String).V dInetAddress add1= InetAddress.getLocalHost();InetAddress add2= InetAddress.getByName(localhost);

  • Lp trnh SocketMy truyn v my nhn thit lp mt kt ni TCP bng socket.

    Socket cho php truyn nhn d liu trn mng TCP/IP

    C hai loi socketTCP (Transmission Control Protocol)UDP (User Datagram Protocol)

  • Socket [1]Java cung cp hai lp i tng lp trnh socketjava.net.Socketjava.net.ServerSocketCc hm khi to ca lp Socket1. public Socket (String host, int port) throws UnknownHostException, IOException2. public Socket (InetAddress address, int port) throws IOException3. public Socket (String host, int port, InetAddress localaddr, int localPort) throws IOException4. public Socket (InetAddress addr, int localport, boolean b ) throws IOException

  • Socket [2]Cc phng thc thao tc trn Socket1. public InputStream getInputStream() throws IOException2. public OutputStream getOutputStream() throws IOException3. public void close() throws IOException

  • ServerSocket [1]Cc hm khi to ca lp ServerSocket1. public ServerSocket (int port)throws IOException2. public ServerSocket (int port, int count)throws IOException3. public ServerSocket (int port, int count, InetAddr localaddr)throws IOException

  • ServerSocket [2]Cc phng thc thao tc trn ServerSocket1. public Socket accept() throws IOException2. public void close() throws IOException

  • Lp trnh Server TCPTo ServerSocketGi thc thi phng thc accept() chp nhn thit lp kt ni vi Client => nhn c Socket giao tip vi Client.Ly InputStream v OutputStream nhn v gi d liu vi Client.Gi v nhn d liu vi Client, s dng cc phng thc read() v write() ca cc lp i tng InputStream v OutputStream.ng Socket v ServerSocketKt thc chng trnh

  • Server TCPServerSocket ssk = new ServerSocket(1234);Socket sk= ssk.accept();InputStream is= sk.getInputStream();OutputStream os= sk.getOutputStream();byte[] buffer= new byte[128];int len= is.read(buffer);System.out.println(new String(buffer,0,len));sk.close();ssk.close();

  • Lp trnh Client TCPTo Socket kt ni n ServerLy InputStream v OutputStream nhn v gi d liu vi Server.Gi v nhn d liu vi Server, s dng cc phng thc read() v write() ca cc lp i tng InputStream v OutputStream.ng SocketKt thc chng trnh

  • Client TCPSocket sk = new Socket(10.0.0.1, 1234);InputStream is= sk.getInputStream();OutputStream os= sk.getOutputStream();String msg=hello;os.write(msg.getBytes());sk.close();

  • DatagramSocket [1]UDP l giao thc cho php gi/nhn tng gi tin n lJava cung cp lp java.net.DatagramSocket lp trnh UDP socketCc hm khi to ca lp DatagramSocket1. public DatagramSocket(int port) throws SocketException2. public DatagramSocket() throws SocketException

  • DatagramSocket [2]Cc phng thc thc tc trn DatagramSocket1. public void send(DatagramPacket p) throws IOException2. public void receive(DatagramPacket p) throws IOException3. public void close()4. public int getLocalPort()

  • DatagramPacket[1]Java cung cp lp i tng DatagramPacket to nhng gi tin s dng cho UDP socket

    Cc hm khi to ca lp DatagramPacket1. public DatagramPacket (byte[] buffer, int length)2. public DatagramPacket (byte[] buffer, int length, InetAddress addr, int port)

  • DatagramPacket [2]Cc phng thc thao tc trn gi tin UDP1. public byte[] getData()2. public int getLength()3. public InetAddress getAddress()4. public int getPort()

  • Lp trnh Server UDP To UDP SocketTo DatagramPacket nhn d liuNhn d liu t Client.ng UDP SocketKt thc chng trnh.

  • Server UDPDatagramSocket dsk= new DatagramSocket(1234);byte[] buffer= new byte[128];DatagramPacket pk= new DatagramPacket(buffer, 128);dsk.receive(pk);System.out.println(Client: + pk.getAddress() + : + pk.getPort());System.out.println(new String(buffer, 0, pk.getLength()));dsk.close();

  • Lp trnh Client UDPTo UDP SocketTo DatagramPacket gi d liuGi d liu n Server.ng UDP SocketKt thc chng trnh.

  • Client UDPDatagramSocket dsk= new DatagramSocket();String msg= abc;InetAddress addr= InetAddress.getByName(10.0.0.1);DatagramPacket pk= new DatagramPacket(msg.getBytes(), msg.length(), addr, 1234);dsk.send(pk);dsk.close();

    **