13-Java Network Programming

Similar documents
자바-11장N'1-502

<4D F736F F F696E74202D20C1A63235C0E520B3D7C6AEBFF6C5A920C7C1B7CEB1D7B7A1B9D628B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

Microsoft PowerPoint - Supplement-03-TCP Programming.ppt [호환 모드]

Microsoft PowerPoint - 04-UDP Programming.ppt

Microsoft PowerPoint - 03-TCP Programming.ppt

(Microsoft PowerPoint - AUTCHEYREGRG.ppt [\310\243\310\257 \270\360\265\345])

<C0CCBCBCBFB52DC1A4B4EBBFF82DBCAEBBE7B3EDB9AE2D D382E687770>

PowerPoint Presentation

class InetAddress3{ public static void main(string[] args) throws Exception{ String url = null ; Scanner reader = new Scanner(System.in); System.out.p

Microsoft PowerPoint - java2-lecture7.ppt [호환 모드]

학습목표 네트워크개요 TCP PORT URL/InetAddress Socket/TCP 을이용한네트워크 2

12-file.key

SMB_ICMP_UDP(huichang).PDF

rmi_박준용_final.PDF

PowerPoint 프레젠테이션

<4D F736F F F696E74202D20B3D7C6AEBFF6C5A9C7C1B7CEB1D7B7A1B9D65F FBCD2C4CF5FC3A4C6C35FBFA1C4DA2E BC8A3C8A

제1장 자바 언어 소개

16장

02 C h a p t e r Java

JMF2_심빈구.PDF

6강.hwp

Connection 8 22 UniSQLConnection / / 9 3 UniSQL OID SET

JMF3_심빈구.PDF

À©µµ³×Æ®¿÷ÇÁ·Î±×·¡¹Ö4Àå_ÃÖÁ¾

Network Programming

Java

<4D F736F F F696E74202D20C1A63234C0E520C0D4C3E2B7C228B0ADC0C729205BC8A3C8AF20B8F0B5E55D>

PowerPoint 프레젠테이션

TCP.IP.ppt

Sena Device Server Serial/IP TM Version

歯NetworkKawuiBawuiBo.PDF

14-Servlet

PowerPoint 프레젠테이션

PowerPoint 프레젠테이션

API STORE 키발급및 API 사용가이드 Document Information 문서명 : API STORE 언어별 Client 사용가이드작성자 : 작성일 : 업무영역 : 버전 : 1 st Draft. 서브시스템 : 문서번호 : 단계 : Docum

USB USB DV25 DV25 REC SRN-475S REC SRN-475S LAN POWER LAN POWER Quick Network Setup Guide xdsl/cable Modem PC DVR 1~3 1.. DVR DVR IP xdsl Cable xdsl C

<4D F736F F F696E74202D E20B3D7C6AEBFF6C5A920C7C1B7CEB1D7B7A1B9D62E >

Microsoft PowerPoint - [EEL2] Lab10.pptx

PWR PWR HDD HDD USB USB Quick Network Setup Guide xdsl/cable Modem PC DVR 1~3 1.. DVR DVR IP xdsl Cable xdsl Cable PC PC DDNS (

Interstage5 SOAP서비스 설정 가이드

FileMaker ODBC and JDBC Guide

PowerPoint Presentation

6주차.key

untitled

07 자바의 다양한 클래스.key

mytalk

hd1300_k_v1r2_Final_.PDF

FileMaker ODBC 및 JDBC 가이드

歯 Final.PDF

Chap12

FileMaker 15 ODBC 및 JDBC 설명서

05-class.key

3ÆÄÆ®-11

chapter4

Network seminar.key

슬라이드 1

Cluster management software

자바 프로그래밍

쿠폰형_상품소개서

Chap7.PDF

10X56_NWG_KOR.indd


1217 WebTrafMon II

untitled


Analytics > Log & Crash Search > Unity ios SDK [Deprecated] Log & Crash Unity ios SDK. TOAST SDK. Log & Crash Unity SDK Log & Crash Search. Log & Cras

슬라이드 제목 없음

SRC PLUS 제어기 MANUAL

비긴쿡-자바 00앞부속

12-file.key

03-JAVA Syntax(2).PDF

PowerPoint 프레젠테이션

Microsoft Word - KPMC-400,401 SW 사용 설명서

1

Subnet Address Internet Network G Network Network class B networ

MasoJava4_Dongbin.PDF

Remote UI Guide

SS Term #3.doc

목차 INDEX JSON? - JSON 개요 - JSONObject - JSONArray 서울시공공데이터 API 살펴보기 - 요청인자살펴보기 - Result Code - 출력값 HttpClient - HttpHelper 클래스작성 - JSONParser 클래스작성 공공

Microsoft PowerPoint - Java7.pptx

제20회_해킹방지워크샵_(이재석)


bn2019_2

Chap06(Interprocess Communication).PDF

FileMaker ODBC and JDBC Guide

Voice Portal using Oracle 9i AS Wireless

untitled

Microsoft PowerPoint - Lecture_Note_5.ppt [Compatibility Mode]

Microsoft PowerPoint - AUTOMATING BESPOKE ATTACKS.pptx

歯9장.PDF

The Pocket Guide to TCP/IP Sockets: C Version

Microsoft PowerPoint - web-part03-ch19-node.js기본.pptx

01-OOPConcepts(2).PDF

NoSQL

Switching

Javascript.pages

J2EE Concepts

09-Java Input Output

Contents Contents 2 1 Abstract 3 2 Infer Checkers Eradicate Infer....

2009년 상반기 사업계획

Transcription:

JAVA Programming Language JAVA Network Programming IP Address(Internet Protocol Address) URL(Uniform Resource Location) TCP(Transmission Control Protocol) Socket UDP(User Datagram Protocol) Client / Server Programming 2

IP Address(1), 32 1 DNS(Domain Name Servic IP Address 3 IP Address(2) 4

IP Address(3) / 5 IP Address(4) (decapsulation). 6

IP Address(5) InetAddress IP Byte[ ]] getaddress( ); );//// InetAddress IP String gethostaddress( ); );/// IP %d.%d.%d.%d String gethostname( ); );//// String tostring( ); );/// IP Boolean ismulticastaddress( ); );/// InetAddress IP // // IP Static InetAddress[ ]] getallbyname(string host); // // IP Static InetAddress getbyname(string host); // // local host IP Static InetAddress getlocalhost( ); ); 7 IP Address(6) InetAddress InetAddressTest InetAddressTest main(string main(string args[]) args[]) InetAddress InetAddress myip=null, myip=null, myips[]=null; myips[]=null; myip myip = InetAddress.getByName(203.253.24.110 InetAddress.getByName(203.253.24.110 ); ); System.out.println(getHostName: System.out.println(getHostName: + myip.gethostname()); myip.gethostname()); System.out.println(getHostAddr: System.out.println(getHostAddr: + myip.gethostaddress()); myip.gethostaddress()); System.out.println( System.out.println( tostring: tostring: + myip.tostring()); myip.tostring()); catch(unknownhostexception catch(unknownhostexception System.out.println(; System.out.println(; myip myip = InetAddress.getByName(selab.soongsil.ac.kr); InetAddress.getByName(selab.soongsil.ac.kr); System.out.println(getHostName: System.out.println(getHostName: + myip.gethostname()); myip.gethostname()); System.out.println(getHostAddr: System.out.println(getHostAddr: + myip.gethostaddress()); myip.gethostaddress()); System.out.println( System.out.println( tostring: tostring: + myip); myip); catch(unknownhostexception catch(unknownhostexception System.out.println(; System.out.println(; myip myip = InetAddress.getLocalHost(); InetAddress.getLocalHost(); System.out.println(getHostName: System.out.println(getHostName: + myip.gethostname()); myip.gethostname()); System.out.println(getHostAddr: System.out.println(getHostAddr: + myip.gethostaddress()); myip.gethostaddress()); catch(unknownhostexception catch(unknownhostexception System.out.println(; System.out.println(; byte byte inet[] inet[] = myip.getaddress(); myip.getaddress(); System.out.print(getHostAddr: System.out.print(getHostAddr: ); ); for(int for(int i=0;i<inet.length;i++) i=0;i<inet.length;i++) System.out.print(inet[i]+.); System.out.print(inet[i]+.); System.out.println(); System.out.println(); System.out.print(getHostAddr: System.out.print(getHostAddr: ); ); for(int for(int i=0;i<inet.length;i++) i=0;i<inet.length;i++) System.out.print(((inet[i]<0) System.out.print(((inet[i]<0)?? (inet[i]+256) (inet[i]+256) : : inet[i])+.); inet[i])+.); System.out.println(); System.out.println(); myips myips = InetAddress.getAllByName(selab.soongsil.ac.kr); InetAddress.getAllByName(selab.soongsil.ac.kr); for(int for(int i=0;i<myips.length;i++) i=0;i<myips.length;i++) System.out.println(getHostName: System.out.println(getHostName: + myips[i].gethostname()); myips[i].gethostname()); System.out.println(getHostAddr: System.out.println(getHostAddr: + myips[i].gethostaddress()); myips[i].gethostaddress()); catch(unknownhostexception catch(unknownhostexception System.out.println(; System.out.println(; 8

URL(Uniform Resource Location) URL <URL > 9 URL(2) URL URL Protocol Host TCP Path Anchor URL ( ref, or reference ) # 10

URL(3) URLEncoder x-www-form-urlencoded MIME + %xy 3 URLDecoder URLEncoder 11 URL(4) URLConnection, URL URL 1. URL openconnection 2. setup parameter 3. connect 4.. 12

URL(5) HTTP(Hyper Text Transfer Protocol) MIME(Multipurpose Internet Mail Extension) HTML 1. (create connection) 2. (request) 3. (respons 4. (close connection) 13 URL(6) HttpURLConnection URLConnection HTTP 14

TCP Socket(1) Socket TCP <IP Address port, socket > 15 TCP Socket(2) C TCP 16

TCP Socket(3) TCP 17 TCP Socket(4), 0 1023 1024 65535 1. 2. echo daytime FTP TELNET SMTP HTTP 7 13 21 23 25 80 18

TCP Socket(5) Socket Socket port <socket> 19 TCP Socket(5) Basic process for JAVA Network Program Step 1 Open a socket Step 2 Open an input stream and output stream to the socket Step 3 Read from and write to the stream according to the server s protocol Step 4 Close the streams Step 5 Close the socket 20

TCP Socket(6) ServerSocket Socket / 21 Establishing a Server Step 1 : create a ServerSocket object Register port number, a maximum number of clients Step 2 : listen indefinitely for an attempt by a client to connect Call to the ServerSocket accept method Step 3 : to get OutputStream, InputStream object Enable the server to communicate with the client Step 4 : the Server and the client communicate Via the InputStream and OutputStream object Step 5 : the server close the connection By invoking the close method on the Socket 22

Establishing a Server - code... // // Step 1: 1: Create a ServerSocket. server = ServerSocket( 5000, 100 ); ); while (( true )) // // Step 2: 2: Wait for for a connection. connection = server.accept(); display.append( Connection + counter + received from: + connection.getinetaddress().gethostname () ());); // // Step 3: 3: Get Get input and output streams. input = DataInputStream( connection.getinputstream() ); ); output = DataOutputStream( connection.getoutputstream() ); ); display.append( \ngot I/O I/O streams\n ); ); // // Step 4: 4: Process connection. display.append( Sending message \Connection successful\\n ); ); output.writeutf ((Connection successful ); ); display.append( Client message: + input.readutf () ());); // // Step 5: 5: Close connection. display.append( \ntransmission complete. + Closing socket.\n\n ); ); connection.close(); ++counter;... 23 Establishing a Client Establishing a Client Step 1 : create a Socket object To connect to the server Step 2 : to get OutputStream, InputStream object To get references to the Socket s associated InputStream and OutputStream Step 3 : the server and the client communicate Via the InputStream and OutputStream object Step 4 : the client close the connection By invoking the close method on the Socket 24

Establishing a Client - code... // // Step 1: 1: Create a Socket to to make connection. client = Socket( InetAddress.getLocalHost(), 5000 ); ); display.append( Connected to: to: + client.getinetaddress().gethostname() ); ); // // Step 2: 2: Get the input and output streams. input = DataInputStream( client.getinputstream() ); ); output = DataOutputStream( client.getoutputstream() ); ); display.append( \ngot I/O Streams\n ); ); // // Step 3: 3: Process connection. display.append( Server message: + input.readutf() ); ); display.append( \nsending message \Thank you.\\n ); ); output.writeutf( Thank you. ); ); // // Step 4: 4: Close connection. display.append( Transmission complete. + Closing connection.\n ); ); client.close();..... 25 TCP Socket(7) ( ) java.net ServerSocket ServerSocket(int port); ServerSocket(int port, int backlog); ServerSocket(int port, int backlog, InetAddress bindaddr); 26

TCP Socket(8) ( ) Backlog Argument, Backlog Backlog,. bindaddr Argument, 27 TCP Socket(9) ServerSocket (EchoServerTest) java.io.*; catch catch (IOException (IOException java.io.*; System.err. System.err. println(failure: println(failure: +; +; System.exit( EchoServerTest EchoServerTest System.exit( 1); 1); main(string[] main(string[] args) args) int int port=4444; port=4444; Socket Socket clientsocket clientsocket = null; null; PrintWriter ServerSocket ServerSocket serversocket serversocket = null; PrintWriter socketout socketout = null; PrintWriter(clientSocket.getOutputStream(), PrintWriter(clientSocket.getOutputStream(), tru; tru; BufferedReader if(args.length if(args.length == == 1) 1) BufferedReader socketin socketin = BufferedReader( BufferedReader( InputStreamReader(clientSocket.getInputStream())); InputStreamReader(clientSocket.getInputStream())); String port port = Integer. Integer. parseint(args[0]); String inputline; inputline; parseint(args[0]); catch(numberformatexception catch(numberformatexception while((inputline port port = 4444; while((inputline = socketin.readline()) socketin.readline())!=!= null) null) 4444; socketout.println(inputlin; socketout.println(inputlin; System.out.println( System.out.println( echo: echo: +inputlin; +inputlin; socketin.close(); socketin.close(); socketout.close(); serversocket serversocket = ServerSocket(port); socketout.close(); ServerSocket(port); clientsocket.close(); clientsocket clientsocket = serversocket.accept(); clientsocket.close(); serversocket.accept(); serversocket.close(); serversocket.close(); System.out.println( System.out.println( serversocket: serversocket: +serversocket); catch catch (IOException (IOException +serversocket); System.out.println(Failure: System.out.println( System.out.println( getlocalport: getlocalport: +serversocket.getlocalport()); System.out.println(Failure: +; +; +serversocket.getlocalport()); System.out.println(); System.out.println(); System.out.print( System.out.print( Connected Connected to: to: +clientsocket.getinetaddress()); +clientsocket.getinetaddress()); System.out.println( System.out.println( : : +clientsocket.getport()); +clientsocket.getport()); 28

TCP Socket(10) ServerSocket (EchoClientTest) System.out.println ( Connected to: +clientsocket.getinetaddress()); java.io.*; System.out.println ( Connected to: +clientsocket.getinetaddress()); java.io.*; System.out.println ( getport: +clientsocket.getport()); System.out.println ( getport: +clientsocket.getport()); System.out.println (getlocaladdress: +clientsocket.getlocaladdress()); System.out.println (getlocaladdress: +clientsocket.getlocaladdress()); System.out.println ( getlocalport: +clientsocket.getlocalport()); System.out.println ( getlocalport: +clientsocket.getlocalport()); EchoClientTest EchoClientTest System.out.print( : ); System.out.print( : ); main(string main(string args[]) while (( inputline = stdin.readline())!= null ) args[]) while (( inputline = stdin.readline())!= null ) int int port; if (inputline.equals(by) port; if (inputline.equals(by) Socket Socket clientsocket=null; break; clientsocket=null; break; PrintWriter PrintWriter socketout=null; socketout=null; socketout.println (inputlin; BufferedReader BufferedReader socketin=null; socketout.println (inputlin; socketin=null; System.out.println ( echo: + socketin.readline()); System.out.println ( echo: + socketin.readline()); System.out.print( : ); System.out.print( : ); if(args.length if(args.length < 2) 2) System.out.println([USAGE] System.out.println([USAGE] java java EchoClientTest EchoClientTest EchoServer EchoServer Port); Port); socketout.close(); socketout.close(); System.exit( System.exit( 1); 1); socketin.close(); socketin.close(); stdin.close(); stdin.close(); clientsocket.close(); clientsocket.close(); port port = Integer. Integer. parseint(args[1]); catch (UnknownHostException parseint(args[1]); catch (UnknownHostException System.out.println (Failure: +; catch(numberformatexception catch(numberformatexception System.out.println (Failure: +; System.exit(1); port port = 4444; System.exit(1); 4444; catch (Exception catch (Exception System.out.println (Failure: +; System.out.println (Failure: +; String String inputline; inputline; BufferedReader BufferedReader stdin stdin = BufferedReader( BufferedReader( InputStreamReader(System.in)); InputStreamReader(System.in)); clientsocket clientsocket = Socket(args[0], Socket(args[0], port); port); socketin socketin = BufferedReader( BufferedReader( InputStreamReader(clientSocket.getInputStream())); InputStreamReader(clientSocket.getInputStream())); socketout socketout = PrintWriter(clientSocket.getOutputStream(), PrintWriter(clientSocket.getOutputStream(), tru; tru; 29 TCP Socket(11) ( ) Socket Socket, I/O stream InputStream / OutputStream getinputstream / getoutputstream Socket(String host, int port); Socket(InetAddress address, int port); // // host,, // // port // // address IP Address 30

TCP Socket(12) Socket (1) java.io.*; java.io.*; EchoPortTest EchoPortTest final final int int ECHO_PORT=7; ECHO_PORT=7; main(string[] main(string[] args) args) Socket Socket socket socket = null; null; PrintWriter PrintWriter socketout socketout = null; null; BufferedReader BufferedReader socketin socketin = null; null; if(args.length if(args.length < 1) 1) System.out.println([USAGE] System.out.println([USAGE] java java EchoPortTest EchoPortTest EchoServer); EchoServer); System.exit( System.exit( 1); 1); socketin.close(); socketin.close(); socketout.close(); socketout.close(); socket.close(); socket.close(); catch(exception catch(exception System.out.println(Failure: +; +; String String inputline; inputline; BufferedReader BufferedReader stdin stdin = BufferedReader( BufferedReader( InputStreamReader(System.in)); InputStreamReader(System.in)); socket socket = Socket(args[0], Socket(args[0], EchoPortTest.ECHO_PORT); EchoPortTest.ECHO_PORT); socketin socketin = BufferedReader( BufferedReader( InputStreamReader(socket.getInputStream())); InputStreamReader(socket.getInputStream())); socketout socketout = PrintWriter(socket.getOutputStream(), PrintWriter(socket.getOutputStream(), tru; tru; while((inputline while((inputline = stdin.readline()) stdin.readline())!=!= null) null) socketout.println(inputlin; socketout.println(inputlin; System.out.println(echo: System.out.println(echo: + socketin.readline()); socketin.readline()); 31 TCP Socket(13) Socket (2) java.io.*; DayTimePortTest final final int intdaytime_port=13; main(string[ ]] args) args) Socket Socket socket socket = null; null; BufferedReader BufferedReader socketin= socketin= null; null; if(args.length if(args.length < 1) 1) System.out.println([USAGE] java javadaytimeporttest DayTimeServer); DayTimeServer); System.exit(1); System.exit(1); socket socket = Socket(args[0],DayTimePortTest.DAYTIME_PORT); socketin= socketin= BufferedReader(InputStreamReader(socket.getInputStream( ))); ))); System.out.println(Day Time: Time: + socketin.readline( socketin.readline( )); )); socketin.close( socketin.close( ); ); socket.close( socket.close( ); ); catch catch (Exception (Exception System.out.println(Failure: +; +; 32

UDP(1) UDP DatagramPacket, DatagramSocket 33 UDP(2) UDP / (UdpDayTimeServerTest) java.io.*; java.io.*; java.util.date; java.util.date; UdpDayTimeServerTest UdpDayTimeServerTest main(string[] main(string[] args) args) DatagramSocket DatagramSocket socket=null; socket=null; DatagramPacket DatagramPacket packetout=null; packetout=null; DatagramPacket DatagramPacket packetin=null; packetin=null; byte byte packetbuf[] packetbuf[] = byte[1024]; byte[1024]; String String datestring=null; datestring=null; socket socket = DatagramSocket(13); DatagramSocket(13); for(;;) for(;;) packetin packetin = DatagramPacket(packetBuf, DatagramPacket(packetBuf, 1024); 1024); socket.receive(packetin); socket.receive(packetin); datestring datestring = String( String( Date(). Date(). togmtstring()+\r\n); togmtstring()+\r\n); int int len len = datestring.length(); datestring.length(); int int port port =packetin.getport(); =packetin.getport(); InetAddress InetAddress inet inet = packetin.getaddress(); packetin.getaddress(); packetout packetout = DatagramPacket(dateString.getBytes(), DatagramPacket(dateString.getBytes(), len, len, inet, inet, port); port); socket.send( socket.send( packetout); packetout); System.out.println( System.out.println( Sending: Sending: + datestring); datestring); catch(ioexception catch(ioexception System.out.println(Failure: System.out.println(Failure: +; +; 34

UDP(3) UDP / (UdpDayTimeServerTest) java.io.*; java.io.*; UdpDayTimeClientTest UdpDayTimeClientTest main(string[] main(string[] args) args) DatagramSocket DatagramSocket socket=null; socket=null; DatagramPacket DatagramPacket packetout=null; packetout=null; DatagramPacket DatagramPacket packetin=null; packetin=null; byte byte packetbuf[] packetbuf[] = byte[1024]; byte[1024]; InetAddress InetAddress serverinet; serverinet; if(args.length if(args.length < 1) 1) System.out.println([USAGE] System.out.println([USAGE] java java UdpClockTest UdpClockTest DayTimeServer); DayTimeServer); System.exit( System.exit( 1); 1); socket socket = DatagramSocket(); DatagramSocket(); serverinet serverinet = InetAddress.getByName(args[0]); InetAddress.getByName(args[0]); packetout packetout = DatagramPacket(packetBuf, DatagramPacket(packetBuf, 2, 2, serverinet, serverinet, 13); 13); packetin packetin = DatagramPacket(packetBuf, DatagramPacket(packetBuf, 1024); 1024); socket.send( socket.send( packetout); packetout); socket.receive(packetin); socket.receive(packetin); String String daytime daytime = String(packetIn.getData(), String(packetIn.getData(), 0, 0, packetin.getlength()); packetin.getlength()); System.out.println(Day System.out.println(Day Time: Time: + daytim; daytim; socket.close(); socket.close(); catch(ioexception catch(ioexception System.out.println(Failure: System.out.println(Failure: +; +; 35 UDP(4) MulticastSocket IP IP D 224.0.0.0 239.255.255.255, UDP 36

UDP(5) // // join a Multicast group and send the the group salutations...... byte[ ]] msg msg = 'H', 'e', 'e','l', 'l', 'l', 'l','o'; InetAddress group = InetAddress.getByName (228.5.6.7); MulticastSocket s = MulticastSocket(6789); s.joingroup(group); DatagramPacket hi hi = DatagramPacket(msg, msg.length, group, 6789); s.send(hi); // // get get their responses! byte[ ]] buf buf = byte[1000]; DatagramPacket recv = DatagramPacket(buf, buf.length); s.receive(recv);...... // // OK, I'm I'm done talking --leave the the group... s.leavegroup(group); 37 / (1) SMTP(Send Mail Transfer Protocol), SMTP. HELO localhost SMTP MAIL FROM: RCPT TO: DATA SUBJECT: >. QUIT 38

/ (2) / Socket ServerSocket Chatting Server Chatting Client 39 / (3) Chatting Server Chatting Client Chatting Client 40