1 / 34

Introduction to Socket Programming

Introduction to Socket Programming. Asst. Prof. Chaiporn Jaikaeo, Ph.D. chaiporn.j@ku.ac.th http://www.cpe.ku.ac.th/~cpj Computer Engineering Department Kasetsart University, Bangkok, Thailand. Outline. Socket API on Java Simple client-server applications Simple web server. Socket API.

ama
Download Presentation

Introduction to Socket Programming

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. Introduction to Socket Programming Asst. Prof. Chaiporn Jaikaeo, Ph.D. chaiporn.j@ku.ac.th http://www.cpe.ku.ac.th/~cpj Computer Engineering Department Kasetsart University, Bangkok, Thailand

  2. Outline • Socket API on Java • Simple client-server applications • Simple web server

  3. Socket API • API for developing applications that perform inter-process communication • most commonly for communications across a computer network • Example functions • listen – used by server to wait for contact from client • connect – used by client to contact server • send – used by either client or server to send data • recv – used by either client or server to receive data • close – close the connection 3

  4. Example - API Calls Client Server connect listen send recv recv send recv send

  5. Internet App App A B Services Provided by Socket API • Connection-oriented, stream-like service • Provides virtual stream-oriented pipe • Data transfer is reliable • No loss, in-order arrival • Both machines use Transmission Control Protocol (TCP) to transfer data

  6. Internet App App A B Services Provided by Socket API • Connectionless, datagram service • User must prepare packet of data before sending • Data transfer is NOT reliable • Loss possible, out-of-order arrival possible • Both machines use User-Datagram Protocol (UDP) to transfer data

  7. Connection-oriented Streaming Service Client Client Server Server Internet Internet Initiates connection Sends datagrams Awaits connection Awaits datagrams Connectionless Datagram Service Client-Server Paradigm • Most common model for Internet applications

  8. Internet Proc4 Ports Proc3 Proc2 Proc1 Proc5 Port Addressing • IP addresses are used to identify hosts (i.e., machines) on the Internet • Port numbers are used to distinguish different processes running on the same host A B IP Address 1 IP Address 2

  9. UDP (Datagram) Socket Applications Using Java/Groovy

  10. Starting Groovy Shell • On Windows, double-click groovysh.bat to start an instance of Groovy shell

  11. Groovy Shell Basics • Most Java statements are acceptable • Most common packages are already imported by default: • java.io.*, java.net.*, java.lang.* • Variables are untyped • No need for declaration • Use inspect <variable> to browse available properties and methods

  12. UDP Socket: Flow in Java Client Server createsocket createsocket send receive receive close close send

  13. Creating Server Socket • Create a datagram socket object and specify the port it listens to • Prepare a buffer to store datagram • Have it wait for client's datagram • Notes: in pure Java • DatagramSocket must be imported from java.net • IOException must be caught server = new DatagramSocket(22222) dgram = new DatagramPacket(new byte[256], 256) server.receive(dgram)

  14. Creating Client Socket • On another machine, create a client socket • Without port specified, client will pick an unused port • Prepare message in a datagram to be sent to the server client = new DatagramSocket() msg = "Hello" // or whatever you want dgram = new DatagramPacket(msg.getBytes(), msg.length())

  15. Finding Out Your IP Address • Windows – Run ipconfig from a command prompt • MacOS/Linux/Unix – Run ifconfig from a terminal

  16. Sending Datagram to Server • Specify receiver's IP address and port in the datagram • Send datagram to server • Call to server.receive() should now return dgram.setAddress(InetAddress.getByName("<server IP>")) dgram.setPort(22222) client.send(dgram)

  17. Extracting Client Message • Message from the client is now stored in dgram (on the server shell) • On the server, try: • Original message can be constructed dgram.getLength() // return data length dgram.getData() // return data bytes msg = new String(dgram.getData(), 0, dgram.getLength())

  18. Identifying Sender's IP and Port • IP address and port of the sender can be retrieved from getAddress() and getPort(), respectively dgram.getAddress() dgram.getPort()

  19. Experiment on your own • Try sending data in the reverse direction • I.e., from server to client • How do you know client's address and port? • Try sending data from one machine without calling receive() method on the other

  20. Closing Socket • Socket should be closed when no longer used • To free up resources such as port, buffer, etc. • Do this on both sides: server.close() client.close()

  21. TCP (Stream) Socket Applications Using Java/Groovy

  22. TCP Socket: Flow in Java Client Server createsocket createsocket send receive accept receive close close send

  23. Creating Server Socket • Create a socket object and identify the port it listens to • This socket is to wait for requests from clients only • It cannot be used to send/receive data • Have it wait for client's request listener = new ServerSocket(22222) server = listener.accept()

  24. Creating Client Socket • Create a client socket (on another machine) • Call to accept() on server should now return client = new Socket("<Server IP>", 22222)

  25. Internet Creating Data Streams • Both server and client sockets provide generic input/output streams for communication • On server: • On client: OutputStream InputStream App App InputStream OutputStream A B ins = new DataInputStream(server.getInputStream()) outs = new DataOutputStream(client.getOutputStream())

  26. Sending Data • Streams previously created can now be used as regular streams • Ask server to wait for data: • Send message from client ins.readUTF() outs.writeUTF("Hello")

  27. Closing Socket • Similar to datagram socket apps, stream sockets should be closed when no longer used • To free up resources such as port, buffer, etc. • Do this on both sides: • If server no longer wants to accept any more connection, close the listening socket as well server.close() client.close() listener.close()

  28. Experiment on your own • Try sending data from server to client • Try instantiating client socket without calling server.accept() • Try sending data from one machine without calling receive() method on the other

  29. Assignment: Throw me your name • I will be running a server on my machine • For each of you • Create a socket to connect to my machine • Then send a message containing real information of: <student id>,<first-last name>,<nickname>,<email>

  30. Application-Layer Protocol Design

  31. Example: Student Info Query • Let us design a simple protocol used by both client and server • Server listens to TCP port 33333 • Server replies information, depending on the command received from the client

  32. Server Code in Java (Partial) • Get complete code from http://www.cpe.ku.ac.th/~cpj/219321/code/StdServer.java public static void main(String[] args) { ServerSocket listener = new ServerSocket(33333); while (true) { Socket server = listener.accept(); BufferedReader reader = new BufferedReader( new InputStreamReader(server.getInputStream())); PrintWriter writer = new PrintWriter(server.getOutputStream(), true); while (true) { String cmd = reader.readLine(); if (cmd.equals("id")) writer.println("35053339"); : } writer.close(); reader.close(); server.close(); } }

  33. Testing Server with Telnet • At a client machine, open a command prompt and type • Telnet is a generic TCP client application C:\> telnet <server IP> 33333 id 35053339 name Chaiporn Jaikaeo age ERROR bye

  34. Assignment: Simple Web Server • Write a program that acts as a simple web server that listens on TCP port 8888 • Always returns HTML contents "Hello World" wrapped in <H1> tag • Try connecting from your web browser • Get template code from • http://www.cpe.ku.ac.th/~cpj/219321/code/WebServer.java

More Related