CS 351 Week 11 Reading: 1. Advanced UNIX Programming: Rochkind, Marc J. Objectives: 1. To learn about System Interprocess Communication (IPC). 2. To learn about Sockets. Concepts: 1. Interprocess Communication 2. Sockets 3. Pipes Outline: 1. Interprocess Communication 2. Sockets a. What Are Sockets b. Functions i. Creation ii. Binding iii. Closing iv. Connecting v. Sending vi. Receiving vii. Listening viii. Accepting 3. Pipes a. Creating b. Example 4. Sockets on UNIX Reference: 1. Socket Abstraction and Interprocess Communication, Ramamurthy B, 2007, http://www.cse.buffalo.edu/~bina/cse421/fall2003/socketsnov13.ppt 2. http://www.geocities.com/siliconvalley/bay/6879/chat.html CS 351 Week 11 Page 1
1. Interprocess Communication CS 351: Week 11 Lecture Notes - Typical applications today consist of many cooperating processes either on the same host or on different hosts. - For example, consider a client-server application. How to share (large amounts of) data? - How to share files and avoid contention issues? - We want a general mechanism that will work for processes irrespective of their location. IPC: Purpose - Data Transfer - Sharing Data - Event Notification - Process Control IPC at different Levels: - Process Level- Pipes - OS Level- Sockets - Plain Language Level- Distriubuted System Methods 2. IPC using Sockets - Sockets are used if we want to communicate between processes that have no common ancestors. - Sockets are used when we want communication between processes that are not necessarily on the same host. - Sockets use names to refer to one another. What are Sockets? - Socket is an abstraction for an end point of communication that can be manipulated with a file descriptor. - It is an abstract object from which messages are sent and received. - Sockets are created within a communication domain just as files are created within a file system. - A communication domain is an abstraction introduced to bundle common properties of processes communicating through sockets. Example: UNIX domain, internet domain. Sockets and Ports: - About 216 ports are available for use by user processes. CS 351 Week 11 Page 2
- Socket is associated with a protocol. - IPC is transmitting a message between sockets in one process to a socket in another process. - Messages sent to particular IP and port number can be received by the process whose socket is associated with that IP and port number. - Processes cannot share ports with other processes within the computer. Can receive messages on different ports. Socket Names: - Applications refer to sockets with their names. - Within communication domains sockets are referred by addresses. - Name to address translation is done outside the OS. Socket Types: - The format in which an address is specified is according to a domain: o AF_UNIX (address format of UNIX) - a path name within the file system, o AF_INET (internet format): network address, port number etc. - Communication style: stream, datagram, raw or sequenced packets o Stream: reliable, error-free, connection-oriented comm. o Datagram: Connectionless, unreliable, message boundaries preserved. Sockets: Functions - Creating a Socket o socket system call create a socket on demand. o int socket(int domain, int type, int protocol) Domain: PF_INET (Internet), PF_UNIX (local) Type: SOCK_STREAM, SOCK_DGRAM, SOCK_RAW Protocol: 0 usually for IP (see /etc/protocols for details) - Binding a Socket o A socket is created without any association to local or destination address. It is possible to bind the socket to a specific host and in it a specific port number. o int bind(int socket struct sockaddr *addr int addr_len) - Closing a socket o close (socid); closes the specified socket. This is done by a process or thread when it no longer needs the socket connection. o close(int socket) - Connecting CS 351 Week 11 Page 3
o A socket is created in an unconnected state, which means that the socket is not associated with any destination. o An application program should call connect to establish a connection before it can transfer data thru reliable stream socket. For datagrams connect is not required but recommended. o int connect(int socket, struct sockaddr *addr, int addr_len) - Sending o Five different system calls : send, sendto, sendmsg, write, writev o send, write and writev work only with connected sockets. No parameter for destination address. Prior connect should be present for communication. o int send(int socket, char *buf, int blen, int flags) - Receiving o Five different calls are available: read, readv, recv, recvfrom, recvmsg o read, readv, and recv are for connection-oriented comm. o int recv(int socket, char *buf, int blen, int flags) - Listening o To avoid having protocols reject incoming request, a server may have to specify how many messages need to be queued until it has time to process them. o Example: listen(socket,length); - Accepting o Wait for the call. o int accept(int socket, struct sockaddr *addr, int addr_len) 3. Pipes - Provides interprocess communication channel - Processes must be on the same machine - Used mostly for filters - A filter is a process that reads from stdin and writes to stdout - Pipe is a communication channel abstraction Process A can write to one end using write system call Process B can read from the other end using read system call - System call - int pipe( int fd[2] ); return 0 upon success 1 upon failure fd[0] is open for reading fd[1] is open for writing CS 351 Week 11 Page 4
- Two coordinated processes created by fork can pass data to each other using a pipe. 4. Sockets in Unix: - When a program calls fork, the newly created process inherits access to all open sockets. - For threads socket identifiers should be defined in the common address space or passed as parameters. - include files : <socket.h>, <un.h> or <in.h>, and other related header files. - When linking add a -lsocket option besides. Lab Exercise: Chat servers connect two or more clients so that the input of one client is output to all other clients. Attempt number zero of a chat server that reads a line of text from the keyboard and prints to the screen is below. No networking is done so the server isn't really a server but does illustrate some of the general structure of a chat server. Implement a chat server that provides network connection with a client? Solution: Java: import java.awt.*; import java.io.*; import java.net.*; import java.util.*; public class Nets { public static void main(string argv[]) { kickoff kickoffobject = new kickoff(); // end of Nets class class kickoff extends Thread { DataInputStream dis; client[] clientarray = new client[100]; int i = 0; int x = 0; String name; kickoff() { start(); public void run() { CS 351 Week 11 Page 5
server serverobject = new server(); void pause (int time) { try { Thread.sleep(time); catch (InterruptedException e) { // end of kickoff class class server extends Thread { read_from_connection readobj; int num = 1; Thread readthread; Socket sock; ServerSocket listen; static int i = 0; static Vector v = new Vector(); server() { start(); public void run() { System.out.println("Server thread started"); try { listen = new ServerSocket(4321); // listen = new ServerSocket(8090); while(true) { readobj = new read_from_connection(listen.accept(), this); System.out.println("connection accepted"); catch (UnknownHostException e ) {System.out.println("can't find host"); catch ( IOException e ) {System.out.println("Error connecting to host"); synchronized void add_to_vector(read_from_connection obj) { v.addelement(obj); CS 351 Week 11 Page 6
synchronized void remove_from_vector(read_from_connection obj) { v.removeelement(obj); synchronized boolean duplicate_name(read_from_connection obj) { read_from_connection readobj; for (int i = 0; i < v.size(); i++) { readobj = (read_from_connection)v.elementat(i); if (readobj.name.equals(obj.name)) return true; return false; synchronized void broadcast_message(string message) { read_from_connection readobj; for (int i = 0; i < v.size(); i++) { readobj = (read_from_connection)v.elementat(i); readobj.pout.println(message); synchronized void list_names(printstream pout, String name) { String line; read_from_connection readobj; pout.println("welcome " + name); "); if (v.size() > 0 ) pout.println("the following people are in the chat room: else pout.println("you are alone in the chat room"); line = ""; int cnt = 0; for (int i = 0; i < v.size(); i++) { CS 351 Week 11 Page 7
readobj = (read_from_connection)v.elementat(i); if (line.equals("")) line += readobj.name; else line += ", " +readobj.name; cnt++; if (cnt == 10) { pout.println(line); line = ""; cnt = 0; if (line!= "") pout.println(line); void pause (int time) { try { Thread.sleep(time); catch (InterruptedException e) { // end of server class class read_from_connection extends Thread { Socket sock; InputStream in; OutputStream out; DataInputStream din; PrintStream pout; int hours; int minutes; int seconds; String name = " "; String request; server serverobj; read_from_connection readobj; read_from_connection(socket sock, server serverobj) { this.sock = sock; this.serverobj = serverobj; start(); public void run() { CS 351 Week 11 Page 8
System.out.println("read_from_connection thread started"); try { in = sock.getinputstream(); out = sock.getoutputstream(); pout = new PrintStream(out); din = new DataInputStream(in); pout.println("you have connected to the chat server, type something to begin"); request = din.readline(); format_message(); if (serverobj.duplicate_name(this)) { pout.println("name already in use - try another"); pout.println("disconecting..."); stop(); sock.close(); room"); serverobj.list_names(pout, name); serverobj.add_to_vector(this); serverobj.broadcast_message(name + " has entered the chat pause(1000); // pause before sending serverobj.broadcast_message(format_message()); while(true) { request = din.readline(); serverobj.broadcast_message(format_message()); catch (UnknownHostException e ) {System.out.println("can't find host"); catch ( IOException e ) { serverobj.remove_from_vector(this); if (name.equals(" ") == false) { serverobj.broadcast_message(name + " has left the chat room"); stop(); String format_message() { String text; String hoursout; String hourss; CS 351 Week 11 Page 9
String minutess; String secondss; String name; int a; int b; int c; text = ""; name = ""; Date date = new Date(); hours = date.gethours(); hourss = Integer.toString(hours); if (hours <= 9) hourss = "0"+hoursS; minutes = date.getminutes(); minutess = Integer.toString(minutes); if (minutes <= 9) minutess = "0"+minutesS; seconds = date.getseconds(); secondss = Integer.toString(seconds); if (seconds <= 9) secondss = "0"+secondsS; hoursout = "[" + hourss + ":" + minutess + ":" + secondss +"]"; a = request.indexof(' '); if (a == -1) return hoursout + " " + name + " - " + text; b = request.indexof(' ', a + 1); if (a == -1) return hoursout + " " + name + " - " + text; name = request.substring(a + 1,b); this.name = name; c = request.length(); text = request.substring(b + 1, c - 1); return hoursout + " " + name + " - " + text; void pause (int time) { try { Thread.sleep(time); catch (InterruptedException e) { // end of read_from_connection CS 351 Week 11 Page 10
class client extends Thread { DataInputStream dis; Socket sock; PrintStream pout; InputStream in; OutputStream out; DataInputStream din; client() { start(); public void run() { System.out.println("client thread started"); try { // sock = new Socket("161.178.105.233", 4321); // work // sock = new Socket("161.178.105.220", 8888); // mike sock = new Socket("161.178.121.1", 4321); // unix server System.out.println("connection made"); in = sock.getinputstream(); out = sock.getoutputstream(); pout = new PrintStream(out); din = new DataInputStream(in); while(true) { String request = din.readline(); System.out.println(request); catch (UnknownHostException e ) {System.out.println("can't find host"); catch ( IOException e ) {System.out.println("Error connecting to host"); // end of client class CS 351 Week 11 Page 11