Socket Programming (C/Java)

Slides:



Advertisements
Similar presentations
Introduction to Sockets Jan Why do we need sockets? Provides an abstraction for interprocess communication.
Advertisements

Socket Programming in C Slides Adapted on Jörn Altmann‘s Slides.
Socket Programming Application Programming Interface.
© 2003 Andrea Calvagna 5/16/2015 Java Sockets and Server Sockets Low Level Network Programming Andrea Calvagna
© 1999 Elliotte Rusty Harold 5/16/2015 Java Sockets and Server Sockets Low Level Network Programming Elliotte Rusty Harold
Jan Java Networking UDP Yangjun Chen Dept. Business Computing University of Winnipeg.
Elementary TCP Sockets Computer Networks Computer Networks Term B10 UNIX Network Programming Vol. 1, Second Ed. Stevens Chapter 4.
Socket programming Tasos Alexandridis 1HY335a - Socket Programming.
Networks: TCP/IP Socket Calls1 Elementary TCP Sockets Chapter 4 UNIX Network Programming Vol. 1, Second Ed. Stevens.
Quick Overview. 2 ISO/OSI Reference Model Application Application Presentation Presentation Session Session Transport Transport Network Network Data Link.
Socket Programming.
Prepared By E. Musa Alyaman1 User Datagram Protocol (UDP) Chapter 5.
1 Java Networking – Part I CS , Spring 2008/9.
EECS122 Communications Networks Socket Programming January 30th, 2003 Jörn Altmann.
1 Socket Interfaces Professor Jinhua Guo CIS527 Fall 2003.
1 L53 Networking (2). 2 OBJECTIVES In this chapter you will learn:  To understand Java networking with URLs, sockets and datagrams.  To implement Java.
Tutorial 8 Socket Programming
UDP: User Datagram Protocol. UDP: User Datagram Protocol [RFC 768] r “bare bones”, “best effort” transport protocol r connectionless: m no handshaking.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
CS 311 – Lecture 18 Outline IPC via Sockets – Server side socket() bind() accept() listen() – Client side connect() Lecture 181CS Operating Systems.
EECS122 Communications Networks Socket Programming January 30th, 2003 Jörn Altmann.
TCP Socket Programming. r An abstract interface provided to the application programmer  File descriptor, allows apps to read/write to the network r Allows.
1 Tutorial on Socket Programming Computer Networks - CSC 458 Department of Computer Science Yukun Zhu (Slides are mainly from Monia Ghobadi, and Amin Tootoonchian,
Babak Esfandiari (based on slides by Qusay Mahmoud)
TCP Socket Programming. r An abstract interface provided to the application programmer  File descriptor, allows apps to read/write to the network r Allows.
Socket programming in C. Socket programming Socket API introduced in BSD4.1 UNIX, 1981 explicitly created, used, released by apps client/server paradigm.
ECE 4110 – Internetwork Programming Client-Server Model.
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Fall 2000Datacom 11 Socket Programming Review Examples: Client and Server-Diagnostics UDP versus TCP Echo.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
Assignment 3 A Client/Server Application: Chatroom.
9/12/2015B.R1 Socket Abstraction and Interprocess Communication B.Ramamurthy CSE421.
Server Sockets: A server socket listens on a given port Many different clients may be connecting to that port Ideally, you would like a separate file descriptor.
Socket Programming in Java CS587x Lecture 4 Department of Computer Science Iowa State University.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
L 2 - 1 3( 1/ 20) : Java Network Programming. The Socket API The previous contents describe client-server interaction that application programs use when.
Socket Programming Lec 2 Rishi Kant. Review of Socket programming Decide which type of socket – stream or datagram. Based on type create socket using.
Networking Tutorial Special Interest Group for Software Engineering Luke Rajlich.
1 Computer Networks An Introduction to Computer Networks University of Tehran Dept. of EE and Computer Engineering By: Dr. Nasser Yazdani Lecture 3: Sockets.
TELE202 Lecture 15 Socket programming 1 Lecturer Dr Z. Huang Overview ¥Last Lecture »TCP/UDP (2) »Source: chapter 17 ¥This Lecture »Socket programming.
CSCE 515: Computer Network Programming UDP Socket Wenyuan Xu Department of Computer Science and Engineering.
Elementary TCP Sockets UNIX Network Programming Vol. 1, Second Ed. Stevens Chapter 4.
Introduction to Socket
CSE/EE 461 Getting Started with Networking. 2 Basic Concepts A PROCESS is an executing program somewhere. –Eg, “./a.out” A MESSAGE contains information.
Socket Programming Tutorial Department of Computer Science Southern Illinois University Edwardsville Fall, 2015 Dr. Hiroshi Fujinoki
Socket Programming Lab 1 1CS Computer Networks.
Sockets Socket = abstraction of the port concept: –Application programs request that the operating system create a socket when one is needed –O.S. returns.
2: Application Layer1 Chapter 2: Application layer r 2.1 Principles of network applications r 2.2 Web and HTTP r 2.3 FTP r 2.4 Electronic Mail  SMTP,
S OCKET P ROGRAMMING IN C Professor: Dr. Shu-Ching Chen TA: HsinYu Ha.
CSCI 330 UNIX and Network Programming Unit XIV: User Datagram Protocol.
Java Programming II Java Network (I) Java Programming II.
Socket Programming. Computer Science, FSU2 Interprocess Communication Within a single system – Pipes, FIFOs – Message Queues – Semaphores, Shared Memory.
1 Spring Semester 2008, Dept. of Computer Science, Technion Internet Networking recitation #7 Socket Programming.
1 CSCD 330 Network Programming Fall 2013 Some Material in these slides from J.F Kurose and K.W. Ross All material copyright Lecture 8a Application.
Agenda Socket Programming The OSI reference Model The OSI protocol stack Sockets Ports Java classes for sockets Input stream and.
Socket Programming in C CS587x Lecture 3 Department of Computer Science Iowa State University.
Socket Programming(1/2). Outline  1. Introduction to Network Programming  2. Network Architecture – Client/Server Model  3. TCP Socket Programming.
Network Programming. These days almost all devices.
1 Socket Interface. 2 Basic Sockets API Review Socket Library TCPUDP IP EthernetPPP ARP DHCP, Mail, WWW, TELNET, FTP... Network cardCom Layer 4 / Transport.
Object-Orientated Analysis, Design and Programming
Sockets and Beginning Network Programming
Assignment 3 A Client/Server Application: Chatroom
CS 1652 Jack Lange University of Pittsburgh
CSI 4118 – UNIVERSITY OF OTTAWA
Implementation of UDP and TCP
Transport layer API: Socket Programming
EE 122: Sockets Kevin Lai September 11, 2002.
Socket Programming Neil Tang 09/08/2008
Internet Networking recitation #8
Presentation transcript:

Socket Programming (C/Java) Ying Cai Socket Programming (C/Java) CS587x Lecture 3 Department of Computer Science Iowa State University What APIs should be provided for programmers to use in their network programming. UPD or TCP; Remote address, Port, Connection setup, data exchange (send/receive); disconnect. CS587x

Internet Socket Socket provides an interface to TCP/UDP Ying Cai Lecture 2 Internet Socket Socket provides an interface to TCP/UDP Allow programs to write networking applications Socket types of interest SOCK_STREAM Maps to TCP in the AF_INET family SOCK_DGRAM Maps to UDP in the AF_INET family AF_INET: Address family Internet PF_INET: Protocol family The AF_ prefix stands for "address family" and the PF_prefix stands for "protocol family". Historically, the intent was that a single protocol family might support multiple address families and that the PF_ value was used to create the socket and the AF_ value was used in socket address structures. But in actuality, a protocol family supporting multiple address families has never been supported and the <sys/socket.h> header defines the PF_ value for a given protocol to be equal to the AF_ value for that protocol. While there is no guarentee that this equality between the two will always be true, should anyone change this for existing protocols, lots of existing code would break. To conform to existing coding practice, we use only the AF_ constants in this text, although you may encounter the PF_ value, mainly in calls to _socket_. CS587x

Client-Server Architecture Ying Cai Lecture 2 Client-Server Architecture response Client Server request Client requests service from server Server responds with sending service or error message to client CS587x

Simple Client-Server Example Ying Cai Lecture 2 Simple Client-Server Example response Client Server request socket() connect() send() recv() close() socket() bind() listen() accept() recv() send() recv() close() Connection establishment Data request Data response End-of-file notification CS587x

Example: Client Programming Ying Cai Lecture 2 Example: Client Programming Create stream socket (socket() ) Connect to server (connect() ) While still connected: send message to server (send() ) receive (recv() ) data from server and process it CS587x

Initializing Socket Getting the file descriptor int cSock; Ying Cai Lecture 2 Initializing Socket Getting the file descriptor int cSock; if ((cSock = socket(AF_INET, SOCK_STREAM, NULL)) < 0) { perror("socket"); printf("Failed to create socket\n"); abort (); } CS587x

Connecting to Server struct hostent *host = gethostbyname(argv[1]); Ying Cai Lecture 2 Connecting to Server struct hostent *host = gethostbyname(argv[1]); unsigned int svrAddr = *(unsigned long *) host->h_addr_list[0]; unsigned short svrPort = atoi(argv[2]); struct sockaddr_in sin; memset (&sin, 0, sizeof(sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = svrAddr; sin.sin_port = htons(svrPort); if (connect(cSock, (struct sockaddr *) &sin, sizeof(sin)) < 0) { fprintf(stderr, "Cannot connect to server\n"); abort(); } struct sockaddr_in { short sin_family; unsigned short sin_port; unsigned long sin_addr; char sin_zero[8]; } CS587x

Sending Packets Needs socket descriptor, Ying Cai Lecture 2 Sending Packets int send_packets(char *buffer, int buffer_len) { sent_bytes = send(cSock, buffer, buffer_len, 0); if (send_bytes < 0) fprintf(stderr, “cannot send. \n”); } return 0; Needs socket descriptor, Buffer containing the message, and Length of the message CS587x

Receiving Packets int receive_packets(char *buffer, int bytes) { Ying Cai Lecture 2 Receiving Packets int receive_packets(char *buffer, int bytes) { int received = 0; int total = 0; while (bytes != 0) received = recv(cSock, buffer[total], bytes); if (received == -1) return –1; if (received == 0) return total; bytes = bytes – received; total = total + received; } return total; CS587x

Example: Server Programming Ying Cai Lecture 2 Example: Server Programming create stream socket (socket() ) Bind port to socket (bind() ) Listen for new client (listen() ) user connects (accept() ) data arrives from client (recv() ) data has to be send to client (send() ) CS587x

Ying Cai Lecture 2 Why bind? Server application needs to call bind() to tell operating system (i.e. network layer) which port to listen Client application does not need bind() Any port can be used to send data The server application will get the port number of the client application through the UDP/TCP packet header Server port must be known by client application in order to connect to the server How to handle if a port has been used by another application? CS587x

Server Programming struct hostent *host = gethostbyname (argv[1]); Ying Cai Server Programming Lecture 2 struct hostent *host = gethostbyname (argv[1]); unsigned int svrAddr = *(unsigned long *) host->h_addr_list[0]; unsigned short svrPort = atoi (argv[2]); struct sockaddr_in sin; memset (&sin, 0, sizeof (sin)); sin.sin_family = AF_INET; sin.sin_addr.s_addr = svrAddr; sin.sin_port = htons (svrPort); /* network byte order (big-endian) */ int svrSock = socket( AF_INET, SOCK_STREAM, 0 ); if (bind(svrSock, (struct sockaddr *) &sin, sizeof(sin)) < 0) { fprintf(stderr, "Cannot bind to network\n"); abort(); } listen(svrSock, 5); /* maximum 5 connections will be queued */ while (1) int cltSock = accept(svrSock, (struct sockaddr *)&cli_addr, &clilen ); /* launch a new thread to take care of this client connection */ /* cli_addr contains the address of the connecting client */ /* clilent is the buffer length that is valid in cli_addr */ /* both cli_addr and clileng are optional */ CS587x

Java Socket Programming Ying Cai Lecture 2 Java Socket Programming CS587x

Java Sokets TCP stream UDP packet java.net.Socket Ying Cai Lecture 2 Java Sokets TCP stream java.net.Socket java.net.ServerSocket UDP packet Java.net.DatagramPacket java.net.DatagramSocket CS587x

Ying Cai Lecture 2 Socket java.net.Socket is used by clients to make a bi-directional connection with server Socket constructors Socket(String hostname, int port) Socket(InetAddress addr, int port) Socket(String hostname, int port, InetAddress localAddr, int localPort) /* specify a specific NIC and port to use */ Socket(InetAddress addr, int port, InetAddress localAddr, int localPort) Creating socket Socket csweb = new Socket(“www.cs.iastate.edu", 80); CS587x

Ying Cai Lecture 2 Socket Input & Output try { String s; Socket socket = new Socket(“www.cs.iastate.edu”, 80); BufferedReader reader = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintStream pstream = new PrintStream(socket.getOutputStream()); pstream.println(“GET /”); while ((s = reader.readLine()) != null) System.out.println(s); } catch (Exception e) System.err.println(“Error: “ + e); Socket() attempts to connect the server immediately Cannot set or change remote host and port Socket constructors may block while waiting for the remote host to respond CS587x

Some Socket Options void setReceiveBufferSize() Ying Cai Lecture 2 Some Socket Options void setReceiveBufferSize() void setSendBufferSize() void setTcpNoDelay() void setSoTimeout() CS587x

ServerSocket A closed ServerSocket cannot be reopened Ying Cai Lecture 2 ServerSocket ServerSocket is used by server to accept client connections ServerSocket constructor public ServerSocket(int port) public ServerSocket(int port, int backlog) public ServerSocket(int port, int backlog, InetAddress networkInterface) Creating a ServerSocket ServerSocket ss = new ServerSocket(80, 50); A closed ServerSocket cannot be reopened CS587x

A Simple Server try { ServerSocket ss = new ServerSocket(2345); Ying Cai Lecture 2 A Simple Server try { ServerSocket ss = new ServerSocket(2345); Socket s = ss.accept(); PrintWriter pw = new PrintWriter(s.getOutputStream()); pw.println("Hello There!"); pw.println("Goodbye now."); s.close(); } catch (IOException ex) System.err.println(ex); CS587x

Sending UDP Datagrams Convert the data into byte array. Ying Cai Lecture 2 Sending UDP Datagrams Convert the data into byte array. Create a DatagramPacket using the array Create a DatagramSocket using the packet and then call send() method Example InetAddress dst = new InetAddess(“cs.iastate.edu"); String s = “This is my datagram packet" byte[] b = s.getBytes(); DatagramPacket dp = new DatagramPacket(b, b.length, dst, 2345); DatagramSocket sender = new DatagramSocket(); sender.send(dp); Note: DatagramPacket object can be reused (e.g., setting different dst and port). CS587x

Receiving UDP Datagrams Ying Cai Lecture 2 Receiving UDP Datagrams Construct an empty DatagramPacket (with a buffer) Pass the object to a DatagramSocket (with a port) Call the DatagramSocket's receive() method The calling thread blocks until a datagram is received byte buffer = new byte[1024]; DatagramPacket incoming = new DatagramPacket(buffer, buffer.length); DatagramSocket ds = new DatagramSocket(2345); ds.receive(incoming); byte[] data = incoming.getData(); String s = new String(data, 0, incoming.getLength()); System.out.println("Port" + incoming.getPort() + " on " + incoming.getAddress() + " sent this message:"); System.out.println(s); CS587x

A Mistake You Want to Avoid Ying Cai Lecture 2 A Mistake You Want to Avoid byte[] buf = new byte[1024]; DatagramPacket incoming = new DatagramPacket(buf, buf.length); DatagramSocket ds = new DatagramSocket(2345); for (;;) { ds.receive(incoming); byte[] data = incoming.getData(); new DataProcessor(data).start(); } class DataProcessor(byte[] data) extends Thread // processing data[] … CS587x

Correct Way byte[] buf = new byte[1024]; Ying Cai Lecture 2 Correct Way byte[] buf = new byte[1024]; DatagramPacket incoming = new DatagramPacket(buf, buf.length); DatagramSocket ds = new DatagramSocket(2345); for (;;) { ds.receive(incoming); byte[] data = new byte[incoming.getLength()]; System.arraycopy(incoming.getData(), 0, data, 0, data.length); new DataProcessor(data).start(); } class DataProcessor(byte[] data) extends Thread // processing data[] … CS587x

Redundant Array of Inexpensive Disk Ying Cai Lecture 2 Redundant Array of Inexpensive Disk                                                                              RAID Management Monitor the health condition of RAID subsystems disks, fans, power supplies, temperatures, etc. Report any failure instantly Provide disaster recovery array rebuild, spare disks reassign, etc. CS587x

Remote and Centralized Storage Management Ying Cai Lecture 2 Remote and Centralized Storage Management CS587x

Homework #1 (due Feb. 3) Client (C code) Ying Cai Lecture 2 Homework #1 (due Feb. 3) Client (C code) (UDP) Send beacon every minute Server (java code) (TCP) Send command and get result back CS587x

Client Design: Two Threads Ying Cai Lecture 2 Client Design: Two Threads BeaconSender: Send the following message to server every minute using UDP datagram struct BEACON { int ID; // randomly generated during startup int StartUpTime; // the time when the client starts char IP[4]; // the IP address of this client int CmdPort; // the client listens to this port for cmd } CmdAgent: Receive and execute remote commands and send results back using TCP socket. You implement two commands: (1) void GetLocalOS(char OS[16], int *valid) // OS[16] contains the local operation system name // valid = 1 indicates OS is valid (2) void GetLocalTime(int *time, int *valid) // time contains the current system clock // valid = 1 indicates time is valid CS587x

Server Design BeaconListener thread ClientAgent(beacon) thread Ying Cai Lecture 2 Server Design BeaconListener thread Receive beacons sent by clients For each new client, spawn a thread called ClientAgent ClientAgent(beacon) thread Send command GetLocalOS() to the corresponding client Get the result back and display the OS Send command GetLocalTime() to the corresponding client Get the result back and display the execution time CS587x

Code Submission and Testing Ying Cai Lecture 2 Code Submission and Testing Email to yingcai@iastate.edu by the deadline You may be asked to run your code on your computer to show it works properly Run the server Open several consoles Run a client on each console the server should be able to detect when a new client shows up by printing out the client’s OS and startup time Kill one client the server should be able to detect the client dies by printing out a message Kill one client and run the client again immediately the serve should be able to detect the client dies and resurrects CS587x