Unformatted text preview:

CS419: Computer NetworksLecture 2: Jan 31, 2004Sockets ProgrammingSlides stolen from Rohan Murty / Hitesh Ballini slides from 2004 CS519Their slides were adapted from Prof. Matthews’ slides from 2003Socket programmingSocket API• introduced in BSD4.1 UNIX, 1981• Sockets are explicitly created, used, released by applications• client/server paradigm • two types of transport service via socket API: – unreliable datagram – reliable, byte stream-oriented a host-local, application-created/owned, OS-controlled interface (a “door”) into whichapplication process can both send and receive messages to/from another (remote or local) application processsocketGoal: learn how to build client/server application that communicate using socketsSocketsSocket: a door between application process and end-end-transport protocol (UCP or TCP)processkernelbuffers,variablessocketcontrolled byapplicationdevelopercontrolled byoperatingsystemhost orserverprocesskernelbuffers,variablessocketcontrolled byapplicationdevelopercontrolled byoperatingsystemhost orserverinternetLanguages and PlatformsSocket API is available for many languages on many platforms:• C, Java, Perl, Python,… • *nix, Windows,…Socket Programs written in any language and running on any platform can communicate with each other!Writing communicating programs in different languages is a good exerciseDecisions• Before you go to write socket code, decide– Do you want a TCP-style reliable, full duplex, connection oriented channel? Or do you want a UDP-style, unreliable, message oriented channel?– Will the code you are writing be the client or the server? • Client: you assume that there is a process already running on another machines that you need to connect to.• Server: you will just start up and wait to be contactedSocket programming with TCPClient must contact server• server process must first be running• server must have created socket (door) that welcomes client’s contactClient 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– Frees up incoming port– allows server to talk with multiple clientsTCP provides reliable, in-ordertransfer of bytes (“pipe”) between client and serverapplication viewpointPseudo code TCP client• Create socket, connectSocket• Do an active connect specifying the IP address and port number of server • Read and Write Data Into connectSocket to Communicate with server• Close connectSocketPseudo code TCP server• Create socket (serverSocket)• Bind socket to a specific port where clients can contact you • Register with the kernel your willingness to listen that on socket for client to contact you • LoopAccept new connection (connectSocket)Read and Write Data Into connectSocket to Communicate with clientClose connectSocketEnd Loop• Close serverSocketClient/server socket interaction: TCP (Java)wait for incomingconnection requestconnectionSocket =welcomeSocket.accept()create socket,port=x, forincoming request:welcomeSocket = ServerSocket()create socket,connect to hostid, port=xclientSocket = Socket()closeconnectionSocketread reply fromclientSocketcloseclientSocketServer (running on hostid)Clientsend request usingclientSocketread request fromconnectionSocketwrite reply toconnectionSocketTCP connection setupTCP Java Client Codeimport java.io.*; import java.net.*; class TCPClient { public static void main(String argv[]) throws Exception { Socket clientSocket = new Socket(“boo.cs.cornell.edu", 6789); DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());BufferedReader inFromServer = new BufferedReader(newInputStreamReader(clientSocket.getInputStream())); outToServer.writeBytes(stuff_to_write); stuff_to_read = inFromServer.readLine(); clientSocket.close(); }}TCP Java Server Code (listening thread)import java.io.*; import java.net.*; class TCPServer { public static void main(String argv[]) throws Exception { ServerSocket listen_socket = new ServerSocket(6789); while(true) { Socket client_socket = listen_socket.accept(); Connection c = new Connection(client_socket);}}}TCP Java Server Code (spawned thread)class Connection extends Thread {while(true) { BufferedReader inFromClient = new BufferedReader(newInputStreamReader(connectionSocket.getInputStream()));DataOutputStream outToClient = new DataOutputStream (connectionSocket.getOutputStream()); inputString = inFromClient.readLine(); …….outToClient.writeBytes(outputString); } }Socket programming with UDPUDP: very different mindset than TCP• no connection just independent messages sent • no handshaking• sender explicitly attaches IP address and port of destination• server must extract IP address, port of sender from received datagram to know who to respond to UDP: transmitted data may be received out of order, or lostapplication viewpointUDP provides unreliabletransferof groups of bytes (“datagrams”)between client and serverPseudo code UDP server• Create socket• Bind socket to a specific port where clients can contact you • Loop(Receive UDP Message from client x)+(Send UDP Reply to client x)*• Close SocketPseudo code UDP client• Create socket• Loop(Send Message To Well-known port of server)+(Receive Message From Server)• Close SocketExample: 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();Createinput streamCreate client socketTranslatehostname to IP address using DNSExample: Java client (UDP), cont.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(); } }Create datagram with


View Full Document

CORNELL CS 419 - Study Notes

Download Study Notes
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Study Notes and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Study Notes 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?