370 likes | 663 Views
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.
E N D
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 • 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
Example - API Calls Client Server connect listen send recv recv send recv send
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
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
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
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
UDP (Datagram) Socket Applications Using Java/Groovy
Starting Groovy Shell • On Windows, double-click groovysh.bat to start an instance of Groovy shell
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
UDP Socket: Flow in Java Client Server createsocket createsocket send receive receive close close send
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)
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())
Finding Out Your IP Address • Windows – Run ipconfig from a command prompt • MacOS/Linux/Unix – Run ifconfig from a terminal
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)
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())
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()
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
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()
TCP (Stream) Socket Applications Using Java/Groovy
TCP Socket: Flow in Java Client Server createsocket createsocket send receive accept receive close close send
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()
Creating Client Socket • Create a client socket (on another machine) • Call to accept() on server should now return client = new Socket("<Server IP>", 22222)
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())
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")
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()
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
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>
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
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(); } }
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
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