User loginNavigationTake FREE online C/C++ test now!Unix / Linux ProgrammingCode search made simpleYour feedback needed!As a webmaster of this site, I regard you as our most important critic and commentator. We value your opinion and want to know what we are doing right, what we could do better and any other words of wisdom you're willing to pass our way. It would be our greatest motivation which will help us in developing areas you would like to see in this site. We hope you will continue to encourage and support us in our future endeavors.
INDIA |
(Slides) Socket Programming TutorialSlideShow TranscriptSlide 1: Socket Programming connecting processes Jignesh Patel Palanivel Rathinam Slide 2: Overview • Introduction to Sockets • A generic Client-Server application • Programming Client-Server in C • Programming Client-Server in Java • References Slide 3: Introduction to Sockets Slide 4: Introduction to Sockets • Why Sockets? – Used for Interprocess communication. • The Client-Server model – Most interprocess communication uses client-server model – Client & Server are two processes that wants to communicate with each other – The Client process connects to the Server process, to make a request for information/services own by the Server. – Once the connection is established between Client process and Server process, they can start sending / receiving information. • What are Sockets? Socket – End-point of interprocess communication. – An interface through which processes can send / receive information Slide 5: Introduction to Sockets • What exactly creates a Socket? – Slide 6: Introduction to Sockets • Socket Types – STREAM – uses TCP which is reliable, stream oriented protocol – DATAGRAM – uses UDP which is unreliable, message oriented protocol – RAW – provides RAW data transfer directly over IP protocol (no transport layer) • Sockets can use – “unicast” ( for a particular IP address destination) – “multicast” ( a set of destinations – 224.x.x.x) – “broadcast” (direct and limited) – “Loopback” address i.e. 127.x.x.x Slide 7: A generic Client-Server application Slide 8: A generic TCP application • algorithm for TCP client – Find the IP address and port number of server – Create a TCP socket – Connect the socket to server (Server must be up and listening for new requests) – Send/ receive data with server using the socket – Close the connection • algorithm for TCP server – Find the IP address and port number of server – Create a TCP server socket – Bind the server socket to server IP and Port number (this is the port to which clients will connect) – Accept a new connection from client • returns a client socket that represents the client which is connected – Send/ receive data with client using the client socket – Close the connection with client Slide 9: A generic UDP application • algorithm for UDP client – Find the IP address and port number of server – Create a UDP socket – Send/ receive data with server using the socket – Close the connection • algorithm for UDP server – Find the IP address and port number of server – Create a UDP server socket – Bind the server socket to server IP and Port number (this is the port to which clients will send) – Send/ receive data with client using the client socket – Close the connection with client Slide 10: Programming Client-Server in C Slide 11: Programming Client-Server in C • The steps involved in establishing a socket on the client side are as follows: – Create a socket with the socket() system call – Connect the socket to the address of the server using the connect() system call – Send and receive data using send() and recv() system calls. • The steps involved in establishing a socket on the server side are as follows: – Create a socket with the socket() system call – Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine. – Listen for connections with the listen() system call – Accept a connection with the accept() system call. This call typically blocks until a client connects with the server. – Send and receive data Slide 12: Programming TCP Client in C Client.c Socket System contain an internet address /* a structure to Call – create an end point for defined in the include file Slide 13: Programming TCP Client in C Client.c server = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,"ERROR, no such host "); exit(0); } bzero((char *) &serv_addr, sizeof(serv_addr)); serv_addr.sin_family = AF_INET; bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr , server->h_length); serv_addr.sin_port = htons(portno); if (connect(sockfd,&serv_addr,sizeof(serv_addr)) < 0) error("ERROR connecting"); Close Recv System Call – send socket descriptor Send System Call – receive a message a socket Connect System Callcloseaamessage to from a a – initiates a connection on printf("Please enter the message: "); socket bzero(buffer,256); fgets(buffer,255,stdin); #include Slide 14: Programming TCP Server in C Server.c #include Slide 15: Programming TCP Server in C Server.c if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) error("ERROR on binding"); listen(sockfd,5); clilen = sizeof(cli_addr); newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen); if (newsockfd < 0) error("ERROR on accept"); bzero(buffer,256); n = recv(newsockfd,buffer,255,0); if (n < 0) error("ERROR reading from socket"); printf("Here is the message: %s ",buffer); n = send(newsockfd,"I got your message",18,0); Accept System Call accepts a to a socket Listen System Call bind a for connections on a Bind System Call – ––listenname connectionon a if (n < 0) error("ERROR writing to socket"); socket close(newsockfd); #include Slide 16: Programming UDP Client in C • The client code for a datagram socket client is the same as that for a stream socket with the following differences. – the socket system call has SOCK_DGRAM instead of SOCK_STREAM as its second argument & IPPROTO_UDP instead of IPPROTO_TCP as its third argument. – there is no connect() system call – instead of send() and recv(), the client uses sendto() and recvfrom() sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); len = sizeof(struct sockaddr_in); while (1) { /* write */ n = sendto(sock,“Got your message ",17, 0,(struct sockaddr *) &server, len); f (n < 0) error("sendto"); /* read */ n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from, len); if (n < 0) error("recvfrom"); } Slide 17: Programming UDP Server in C • Server code with a datagram socket is similar to the stream socket code with following differences. – Servers using datagram sockets do not use the listen() or the accept() system calls. – After a socket has been bound to an address, the program calls recvfrom() to read a message or sendto() to send a message. sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); len = sizeof(struct sockaddr_in); while (1) { /* read */ n = recvfrom(sock,buf,1024,0,(struct sockaddr *)&from, len); if (n < 0) error("recvfrom"); /* write */ n = sendto(sock,"Got your message ",17, 0,(struct sockaddr *)&from, len); f (n < 0) error("sendto"); } Slide 18: Programming Client-Server in C • In case of Windows Everything in the code is same as described previously except the following differences – You have to tell your compiler to link in the Winsock library, usually called wsock32.lib or winsock32.lib – On Visual C++, this can be done through the Project menu, under Settings.... Click the Link tab, and look for the box titled "Object/library modules". Add "wsock32.lib" to that list. – On Visual Studio .NET, add “wsock32.lib” under Project menu, Properties -> Linker -> Input -> Additional Dependencies #include Slide 19: Programming Client-Server in Java Slide 20: Programming TCP Client-Server in Java • All the classes related to sockets are in the java.net package, so make sure to import that package when you program sockets. • All the input/output stream classes are in the java.io package, include this also • How to open a socket? – If you are programming a client, then you would create an object of Socket class – Machine name is the machine you are trying to open a connection to, – PortNumber is the port (a number) on which the server you are trying to connect to is running. select one that is greater than 1,023! Why?? Socket MyClient; try { MyClient = new Socket("Machine name", PortNumber); } catch (IOException e) { System.out.println(e); } Slide 21: Programming TCP Client-Server in Java • If you are programming a server, then this is how you open a socket: ServerSocket MyService; try { MyServerice = new ServerSocket(PortNumber); } catch (IOException e) { System.out.println(e); } • When implementing a server you also need to create a socket object from the ServerSocket in order to listen for and accept connections from clients. Socket clientSocket = null; try { clientSocket = MyService.accept(); } catch (IOException e) { System.out.println(e); } Slide 22: Programming TCP Client-Server in Java • How to create an input stream? – On the client side, you can use the DataInputStream class to create an input stream to receive response from the server: DataInputStream input; try { input = new DataInputStream(MyClient.getInputStream()); } catch (IOException e) { System.out.println(e); } – The class DataInputStream allows you to read lines of text and Java primitive data types in a portable way. It has methods such as read, readChar, readInt, readDouble, and readLine,. – On the server side, you can use DataInputStream to receive input from the client: DataInputStream input; try { input = new DataInputStream(clientSocket.getInputStream()); } catch (IOException e) { System.out.println(e); } Slide 23: Programming TCP Client-Server in Java • How to create an output stream? – On the client side, you can create an output stream to send information to the server socket using the class PrintStream or DataOutputStream of java.io: PrintStream output; try { output = new PrintStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); } – The class PrintStream has methods for displaying textual representation of Java primitive data types. Its write and println methods are important. Also, you may want to use the DataOutputStream: DataOutputStream output; try { output = new DataOutputStream(MyClient.getOutputStream()); } catch (IOException e) { System.out.println(e); } – Many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one. Slide 24: Programming TCP Client-Server in Java • On the server side – you can use the class PrintStream to send information to the client. PrintStream output; try { output = new PrintStream(clientSocket.getOutputStream()); } catch (IOException e) { System.out.println(e); } • Note: You can use the class DataOutputStream as mentioned previously. Slide 25: Programming TCP Client-Server in Java • How to close sockets? – You should always close the output and input stream before you close the socket. – On the client side: try { output.close(); input.close(); MyClient.close(); } catch (IOException e) { System.out.println(e); } – On the server side: try { output.close(); input.close(); clientSocket.close(); MyService.close(); } catch (IOException e) { System.out.println(e); } Slide 26: Programming UDP Client-Server in Java • How to open a datagram socket? – If you are programming a client, then you would create an object of DatagramSocket class try { DatagramSocket socket = new DatagramSocket(); } catch (IOException e) { System.out.println(e); } • If you are programming a server, then this is how you open a socket: DatagramSocket socket = null; try { socket = new DatagramSocket(4445); } catch (IOException e) { System.out.println(e); } Slide 27: Programming UDP Client-Server in Java • How to send/receive on Datagram sockets? – On the client side, you can use the DatagramPacket class – To send data byte[] buf = new byte[256]; InetAddress address = InetAddress.getByName(args[0]); DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445); socket.send(packet); – To receive data packet = new DatagramPacket(buf, buf.length); socket.receive(packet); String received = new String(packet.getData()); System.out.println(“Received from server: " + received); Slide 28: Programming UDP Client-Server in Java • How to send/receive on Datagram sockets? – On the Server side, you can use the DatagramPacket class – To receive data byte[] buf = new byte[256]; DatagramPacket packet = new DatagramPacket(buf, buf.length); socket.receive(packet); • To send data InetAddress address = packet.getAddress(); int port = packet.getPort(); packet = new DatagramPacket(buf, buf.length, address, port); socket.send(packet); • How to close a Datagram socket? socket.close(); Slide 29: References • Man pages in Linux Accesssible through following command – man 2
|