1 / 36

SOCKET PROGRAMMING IN JAVA

SOCKET PROGRAMMING IN JAVA. Questions that will be Addressed. What mechanisms are available for a programmer who writes network applications? How to write a network application that sends packets between hosts (client and server) across an IP network? Answer: socket API. IP Network. Client.

Télécharger la présentation

SOCKET PROGRAMMING IN JAVA

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. SOCKET PROGRAMMING IN JAVA

  2. Questions that will be Addressed • What mechanisms are available for a programmer who writes network applications? • How to write a network application that sends packets between hosts (client and server) across an IP network? • Answer: socket API IP Network Client Server

  3. e.g. ftp Application Layer e.g. TCP, UDP Transport Layer e.g. IP Network Layer Ethernet Link Layer Layers of the IP Protocol Suite Application Layer Transport Layer Network Layer Link Layer

  4. Location Applications(e.g. browser, game, ftp) Application ProgrammingInterface (API)(e.g. network API) Operating System(e.g. Unix) Interface to the Network Card Network Card & Device Driver(e.g. Ethernet card) PROTOCOL SUITE LOCATION Application Layer • Internet Protocol Layer Transport Layer (TCP, UDP) Network Layer (IP) Link Layer

  5. Network API • Operating system provides Application Programming Interface (API) for network application • API is defined by a set of function types, data structures, and constants • Desirable characteristics of the network interface • Simple to use • Flexible • independent from any application • allows program to use all functionality of the network • Standardized • allows programmer to learn once, write anywhere • Application Programming Interface for networks is called socket

  6. Sockets • Sockets : a door between application process and transport protocol (TCP, UDP). • Sockets provide mechanisms to communicate between computers across a network • There are different kind of sockets • DARPA Internet addresses (Internet Sockets) • Unix interprocess communication (Unix Sockets) • CCITT X.25 addresses • and many others • Berkeley sockets is the most popular Internet Socket • runs on Linux, FreeBSD, OS X, Windows • fed by the popularity of TCP/IP

  7. Types of Internet Sockets • Different types of sockets implement different communication types (stream vs. datagram) • Type of socket: stream socket • connection-oriented • two way communication • reliable (error free), in order delivery • can use the Transmission Control Protocol (TCP) • e.g. telnet, ssh, http • Type of socket: datagram socket • connectionless, does not maintain an open connection, each packet is independent • can use the User Datagram Protocol (UDP) • e.g. IP telephony • Other types exist: similar to the one above

  8. Socket ACCESS • Support stream and datagram packets (e.g. TCP, UDP, IP) • Is Similar to UNIX file I/O API (provides a file descriptor)

  9. Naming and Addressing • Host name • identifies a single host • variable length string (e.g. www.berkeley.edu) • is mapped to one or more IP addresses • IP Address • written as dotted octets (e.g. 10.0.0.1) • 32 bits. Not a number! But often needs to be converted to a 32-bit to use. • Port number • identifies a process on a host • 16 bit number

  10. Client-Server Architecture response • Client requests service to server • Server responds with sending service or error message to client Client Server request

  11. Simple Client-Server Example response Client Server request socket()connect()send()recv()close() socket()accept()recv()send()recv()close() Connectionestablishment Data request Data response End-of-file notification

  12. UDP: no “connection” between client and server no handshaking sender explicitly attaches IP address and port of destination to each packet UDP: transmitted data may be received out of order, or lost SOCKET PROGRAMMING WITH UDP

  13. DatagramSocket(int port) Create DatagramSocket object with port number Methods void receive(DatagramPacket packet) – socket의 정보를 읽어들여 packet에 저장 void send(DatagramPacket packet) – packet을 socket을 통해서 전송 void close() – socket을 close Class Datagramsocket

  14. Client create socket, Port=6434, for incoming request: serverSocket = DatagramSocket() create socket, clientSocket = DatagramSocket() Create, address (hostid, port=6434, send datagram request using clientSocket read request from serverSocket write reply to serverSocket specifying client host address, port number read reply from clientSocket close clientSocket CLIENT/SERVER SOCKET INTERACTION: UDP Server (running on hostid) 2: Application Layer

  15. EXAMPLE: JAVA CLIENT (UDP) import java.io.*; import java.net.*; class UDPClient { public static void main(String args[]) throws Exception { BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); DatagramSocket clientSocket = new DatagramSocket(); InetAddress IPAddress = InetAddress.getByName("hostname"); byte[] sendData = new byte[1024]; byte[] receiveData = new byte[1024]; String sentence = inFromUser.readLine(); sendData = sentence.getBytes(); Create input stream Create client socket 2: Application Layer Translate hostname to IP address using DNS

  16. Example: Java client (UDP), cont. Create datagram with data-to-send, length, IP addr, port DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, 9876); clientSocket.send(sendPacket); DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); clientSocket.receive(receivePacket); String modifiedSentence = new String(receivePacket.getData()); System.out.println("FROM SERVER:" + modifiedSentence); clientSocket.close(); } } Send datagram to server Read datagram from server 2: Application Layer

  17. Example: Java server (UDP) import java.io.*; import java.net.*; class UDPServer { public static void main(String args[]) throws Exception { DatagramSocket serverSocket = new DatagramSocket(9876); byte[] receiveData = new byte[1024]; byte[] sendData = new byte[1024]; while(true) { DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length); serverSocket.receive(receivePacket); Create datagram socket at port 9876 2: Application Layer Create space for received datagram Receive datagram

  18. Example: Java server (UDP), cont String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivePacket.getAddress(); int port = receivePacket.getPort(); String capitalizedSentence = sentence.toUpperCase(); sendData = capitalizedSentence.getBytes(); DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, IPAddress, port); serverSocket.send(sendPacket); } } } Get IP addr port #, of sender Create datagram to send to client 2: Application Layer Write out datagram to socket End of while loop, loop back and wait for another datagram

  19. public class Receiver { public static void main(String args[]) { byte[] data = new byte[20]; DatagramPacket packet = new [ 1 ](data,data.length); DatagramSocket socket = null; try { socket = new [ 2 ] (5555); socket.[ 3 ] (packet); socket.close(); } catch(IOException e) {} System.out.println("Data="+new String(packet.getData())); System.out.println("Length="+packet.getLength()); System.out.println("From="+packet.getAddress()); System.out.println("Port="+packet.getPort()); }} Quiz. public class Sender { public static void main(String args[]) { BufferedReader in = null; String message = null; try { in = new BufferedReader( new InputStreamReader(System.in)); message = in.readLine(); } catch (IOException e) {} byte[] data = message.getBytes(); DatagramPacket packet = null; try { packet = new DatagramPacket(data,data.length, InetAddress.getByName("localhost"),5555); } catch(UnknownHostException e) {} DatagramSocket socket = null; try { socket = new DatagramSocket(); socket.send(packet); socket.close(); } catch(IOException e){} }}

  20. ANSWER • 1: DatagramPacket • 2: DatagramSocket • 3: receive

  21. process process TCP with buffers, variables TCP with buffers, variables socket socket SOCKET-PROGRAMMING USING TCP TCP service: reliable transfer of bytesfrom one process to another controlled by application developer controlled by application developer controlled by operating system controlled by operating system internet host or server host or server

  22. Client must contact server server process must first be running server must have created socket (door) that welcomes client’s contact Client contacts server by: creating client-local TCP socket specifying IP address, port number of server process When client creates socket: client TCP establishes connection to server TCP When contacted by client, server TCP creates new socket for server process to communicate with client allows server to talk with multiple clients source port numbers used to distinguish clients SOCKET PROGRAMMING WITH TCP 2: Application Layer

  23. ServerSocket(int port) client를 받아들일 ServerSocket 생성 Methods Socket accept() – client의 TCP연결 요청을 받아들이고 연결을 담당할 socket을 반환 void close() – socket을 close Class serversocket

  24. Socket(String host, int port) or (InetAddress addr, int port) 접속할 서버주소/포트번호 로 TCP연결요청 Methods InputStream getInputStream() – socket에 연결된 입력stream 반환 OutputStream getOutputStream() – socket에 연결된 출력stream 반환 InetAddress getInetAddress() – 상대방의 InetAddress정보 InetAddress getLocalAddress() – 자신의 InetAddress정보 int getPort() – 상대방 port number int getLocalPort() – 자신의 port number void close() – socket close Class socket

  25. create socket, connect to hostid, port=6434 create socket, port=6434, for incoming request: clientSocket = Socket() welcomeSocket = ServerSocket() TCP connection setup wait for incoming connection request connectionSocket = welcomeSocket.accept() send request using clientSocket read request from connectionSocket write reply to connectionSocket read reply from clientSocket close connectionSocket close clientSocket CLIENT/SERVER SOCKET INTERACTION: TCP Server (running on hostid) Client 2: Application Layer

  26. Example 1 : Client Programming • Create stream socket (socket()) • Create Input,Output streams and attach to socket • While still connected: • Write(read) data to(from) input(output) stream • Close TCP connection and Socket (close())

  27. public class SimpleClient { public static void main(String args[]) throws IOException { Socket s; DataOutputStream dos; s = new Socket("localhost",6434); dos = new DataOutputStream(s.getOutputStream()); dos.writeUTF(“Hello Dr.Han"); dos.close(); s.close(); }}

  28. example 2 : Server Programming • Create server socket (ServerSocket() ) • Bind port to socket • Listen for new client • While • accept user connection and create a new socket (accept() ) • Create Input,Output streams and attach to socket • Write(read) data to(from) input(output) stream • Close TCP connection and Socket (close())

  29. public class SimpleServer { public static void main(String args[]) { ServerSocket s = null; Socket schild; DataInputStream dis; s = new ServerSocket(6434); while(true) { schild = s.accept(); dis = new DataInputStream(schild.getInputStream()); String str = new String (dis.readUTF()); System.out.println(str); dis.close(); schild.close(); } s.close(); }}

  30. Server: Alternative Ways of Handling Many Clients • Forking a new process for each client: • But, creating new process is expensive. • Multithreaded implementation: have one thread handling each client. • Thread is like a process but light-weighted.

  31. Example client-server app: 1) client reads line from standard input (inFromUser stream) , sends to server via socket (outToServer stream) 2) server reads line from socket 3) server converts line to uppercase, sends back to client 4) client reads, prints modified line from socket (inFromServer stream) SOCKET PROGRAMMING WITH TCP 2: Application Layer

  32. EXAMPLE: JAVA CLIENT (TCP) import java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { String sentence; String modifiedSentence; BufferedReader inFromUser = new BufferedReader(new InputStreamReader(System.in)); Socket clientSocket = new Socket("hostname", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); 2: Application Layer Create input stream Create client socket, connect to server Create output stream attached to socket

  33. Example: Java client (TCP), cont. Create input stream attached to socket BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); sentence = inFromUser.readLine(); outToServer.writeBytes(sentence + '\n'); modifiedSentence = inFromServer.readLine(); System.out.println("FROM SERVER: " + modifiedSentence); clientSocket.close(); } } Send line to server 2: Application Layer Read line from server

  34. Example: Java server (TCP) import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { String clientSentence; String capitalizedSentence; ServerSocket welcomeSocket = new ServerSocket(6789); while(true) { Socket connectionSocket = welcomeSocket.accept(); BufferedReader inFromClient = new BufferedReader(new InputStreamReader(connectionSocket.getInputStream())); Create welcoming socket at port 6789 2: Application Layer Wait, on welcoming socket for contact by client Create input stream, attached to socket

  35. Example: Java server (TCP), cont DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream()); clientSentence = inFromClient.readLine(); capitalizedSentence = clientSentence.toUpperCase() + '\n'; outToClient.writeBytes(capitalizedSentence); } } } Create output stream, attached to socket Read in line from socket 2: Application Layer Write out line to socket End of while loop, loop back and wait for another client connection

  36. public class Peer { protected Vector handlers; public static ServerSocket server = null; public static void main(String[] args) { Peer p = new Peer(); } public Peer () { server = new ServerSocket (inPort); handlers = new Vector(); while(true) { Socket client = server.accept(); ChatHandler c = new ChatHandler(this,client); handlers.addElement(c); Thread myThread = new Thread(c); myThread.start(); } } public static void sendRequest(String msg) { Socket s = new Socket(ipaddr, port); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s.getOutputStream())); bw.write(msg); bw.flush(); s.close(); } } class ChatHandler implements Runnable { protected Peer peer; protected Socket socket; protected InputStream ins; public ChatHandler(Peer peer2, Socket s) throws IOException { this.peer = peer2; this.socket = s; ins = socket.getInputStream(); } private String readLine() { String str = new String(); while ((i = ins.read()) != '\n') { str = str.concat(String.valueOf((char) i)); } return str; } public void run() { Socket s2; String msg = readLine(); InetAddress is = socket.getInetAddress(); s2 = new Socket(is.getHostAddress(),this.peer.outPort); BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(s2.getOutputStream())); bw.write(msg); bw.flush(); peer.handlers.removeElement(this); ins.close(); socket.close(); } // run() } // class 끝

More Related