Socket Programming
اسلاید 1: Socket Programming Jignesh PatelPalanivel Rathinamconnecting processes
اسلاید 2: OverviewIntroduction to SocketsA generic Client-Server applicationProgramming Client-Server in CProgramming Client-Server in JavaReferences
اسلاید 3: Introduction to Sockets
اسلاید 4: Introduction to SocketsWhy Sockets?Used for Interprocess communication.The Client-Server modelMost interprocess communication uses client-server modelClient & Server are two processes that wants to communicate with each otherThe 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?End-point of interprocess communication.An interface through which processes can send / receive informationSocket
اسلاید 5: Introduction to SocketsWhat exactly creates a Socket?<IP address, Port #> tupleWhat makes a connection?{Source<IP address, Port #> , Destination <IP address, Port #>} i.e. source socket – destination socket pair uniquely identifies a connection.ExampleServerClientClient192.168.0.1192.168.0.2192.168.0.28013435488Client192.168.0.31343
اسلاید 6: Introduction to SocketsSocket TypesSTREAM – uses TCP which is reliable, stream oriented protocolDATAGRAM – uses UDP which is unreliable, message oriented protocolRAW – 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
اسلاید 7: A generic Client-Server application
اسلاید 8: A generic TCP applicationalgorithm for TCP clientFind the IP address and port number of serverCreate a TCP socketConnect the socket to server (Server must be up and listening for new requests)Send/ receive data with server using the socketClose the connection algorithm for TCP serverFind the IP address and port number of serverCreate a TCP server socketBind 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 connectedSend/ receive data with client using the client socketClose the connection with client
اسلاید 9: A generic UDP applicationalgorithm for UDP clientFind the IP address and port number of serverCreate a UDP socketSend/ receive data with server using the socketClose the connection algorithm for UDP serverFind the IP address and port number of serverCreate a UDP server socketBind 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 socketClose the connection with client
اسلاید 10: Programming Client-Server in C
اسلاید 11: Programming Client-Server in CThe 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
اسلاید 12: Programming TCP Client in C#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h> void error(char *msg){ perror(msg); exit(0);}int main(int argc, char *argv[]){ int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; if (argc < 3) { fprintf(stderr,usage %s hostname portn, argv[0]); exit(0); } portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sockfd < 0) error(ERROR opening socket); /* a structure to contain an internet address defined in the include file <netinet/in.h> */struct sockaddr_in { short sin_family; /* should be AF_INET */ u_short sin_port; struct in_addr sin_addr; char sin_zero[8]; /* not used, must be zero */};struct in_addr { unsigned long s_addr;}; Client.c
اسلاید 13: Programming TCP Client in C#include <stdio.h>#include <sys/types.h>#include <sys/socket.h>#include <netinet/in.h>#include <netdb.h> void error(char *msg){ perror(msg); exit(0);}int main(int argc, char *argv[]){ int sockfd, portno, n; struct sockaddr_in serv_addr; struct hostent *server; char buffer[256]; if (argc < 3) { fprintf(stderr,usage %s hostname portn, argv[0]); exit(0); } portno = atoi(argv[2]); sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if (sockfd < 0) error(ERROR opening socket); Client.cSocket System Call – create an end point for communication#include <sys/types.h>#include <sys/socket.h>int socket(int domain, int type, int protocol);Returns a descriptordomain: selects protocol family e.g. PF_IPX, PF_X25, PF_APPLETALKtype: specifies communication semantics e.g. SOCK_DGRAM, SOCK_RAWprotocol: specifies a particular protocol to be used e.g. IPPROTO_UDP, IPPROTO_ICMP
اسلاید 14: Programming TCP Client in Cserver = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,ERROR, no such hostn); 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); printf(Please enter the message: ); bzero(buffer,256); fgets(buffer,255,stdin); n = send(sockfd,buffer,strlen(buffer),0); if (n < 0) error(ERROR writing to socket); bzero(buffer,256); n = recv(sockfd,buffer,255,0); if (n < 0) error(ERROR reading from socket); printf(%sn,buffer); close(sockfd); return 0;} Client.cConnect System Call – initiates a connection on a socket#include <sys/types.h>#include <sys/socket.h>int connect( int sockfd, const struct sockaddr *serv_addr,socklen_t addrlen);Returns 0 on successsockfd: descriptor that must refer to a socketserv_addr: address to which we want to connectaddrlen: length of serv_addr
اسلاید 15: Programming TCP Client in Cserver = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,ERROR, no such hostn); 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); printf(Please enter the message: ); bzero(buffer,256); fgets(buffer,255,stdin); n = send(sockfd,buffer,strlen(buffer),0); if (n < 0) error(ERROR writing to socket); bzero(buffer,256); n = recv(sockfd,buffer,255,0); if (n < 0) error(ERROR reading from socket); printf(%sn,buffer); close(sockfd); return 0;} Client.cSend System Call – send a message to a socket#include <sys/types.h>#include <sys/socket.h>int send( int s, const void *msg, size_t len, int flags);Returns number of characters sent on successs: descriptor that must refer to a socket in connected statemsg: data that we want to sendlen: length of dataflags: use default 0. MSG_OOB, MSG_DONTWAIT
اسلاید 16: Programming TCP Client in Cserver = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,ERROR, no such hostn); 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); printf(Please enter the message: ); bzero(buffer,256); fgets(buffer,255,stdin); n = send(sockfd,buffer,strlen(buffer),0); if (n < 0) error(ERROR writing to socket); bzero(buffer,256); n = recv(sockfd,buffer,255,0); if (n < 0) error(ERROR reading from socket); printf(%sn,buffer); close(sockfd); return 0;} Client.cRecv System Call – receive a message from a socket#include <sys/types.h>#include <sys/socket.h>int recv( int s, const void *buff, size_t len, int flags);Returns number of bytes received on successs: descriptor that must refer to a socket in connected statebuff: data that we want to receive len: length of dataflags: use default 0. MSG_OOB, MSG_DONTWAIT
اسلاید 17: Programming TCP Client in Cserver = gethostbyname(argv[1]); if (server == NULL) { fprintf(stderr,ERROR, no such hostn); 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); printf(Please enter the message: ); bzero(buffer,256); fgets(buffer,255,stdin); n = send(sockfd,buffer,strlen(buffer),0); if (n < 0) error(ERROR writing to socket); bzero(buffer,256); n = recv(sockfd,buffer,255,0); if (n < 0) error(ERROR reading from socket); printf(%sn,buffer); close(sockfd); return 0;} Client.cClose System Call – close a socket descriptor#include <unistd.h>int close( int s);Returns 0 on successs: descriptor to be closed
اسلاید 18: Programming TCP Server in C#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> void error(char *msg){ perror(msg); exit(0);}int main(int argc, char *argv[]){ int sockfd, newsockfd, portno, clilen; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; int n; if (argc < 2) { fprintf(stderr,ERROR, no port providedn); exit(1); } sockfd = socket(AF_INET, SOCK_STREAM, 0); if (sockfd < 0) error(ERROR opening socket); bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_addr.s_addr = INADDR_ANY; serv_addr.sin_port = htons(portno); Server.c
اسلاید 19: Programming TCP Server in Cif (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: %sn,buffer); n = send(newsockfd,I got your message,18,0); if (n < 0) error(ERROR writing to socket);close(newsockfd);close(sockfd); return 0; } Server.cBind System Call – bind a name to a socket#include <sys/types.h>#include <sys/socket.h>int bind( int sockfd, const struct sockaddr *serv_addr,socklen_t addrlen);Returns 0 on successsockfd: descriptor that must refer to a socketserv_addr: address to which we want to connectaddrlen: length of serv_addr
اسلاید 20: Programming TCP Server in Cif (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: %sn,buffer); n = send(newsockfd,I got your message,18,0); if (n < 0) error(ERROR writing to socket);close(newsockfd);close(sockfd); return 0; } Server.cListen System Call – listen for connections on a socket#include <sys/types.h>#include <sys/socket.h>int listen( int s, int backlog);Returns 0 on successs: descriptor that must refer to a socketbacklog: maximum length the queue for completely established sockets waiting to be acceptedaddrlen: length of serv_addr
اسلاید 21: Programming TCP Server in Cif (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: %sn,buffer); n = send(newsockfd,I got your message,18,0); if (n < 0) error(ERROR writing to socket);close(newsockfd);close(sockfd); return 0; } Server.cAccept System Call – accepts a connection on a socket#include <sys/types.h>#include <sys/socket.h>int accept( int sockfd, const struct sockaddr *addr,socklen_t addrlen);Returns a non-negative descriptor on successsockfd: descriptor that must refer to a socketaddr: filled with address of connecting entityaddrlen: length of addr
اسلاید 22: Programming UDP Client in CThe 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 messagen,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);}
اسلاید 23: Programming UDP Server in Csock = 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 messagen,17, 0,(struct sockaddr *)&from, len); f (n < 0) error(sendto); } 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.
اسلاید 24: Programming Client-Server in C#include <winsock.h>…..void main(int argc,char *argv[]){WSADATA wsda; // if this doesn’t work// WSAData wsda; // then try thisWSAStartup(0x0101,&wsda);…..WSACleanup();closesocket(sockfd);} In case of Windows Everything in the code is same as described previously except the following differencesYou 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
اسلاید 25: Programming Client-Server in Java
اسلاید 26: Programming TCP Client-Server in JavaAll the classes related to sockets are in the java.net package, so makesure to import that package when you program sockets.All the input/output stream classes are in the java.io package, include this alsoHow to open a socket?If you are programming a client, then you would create an object of Socket classMachine 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 toconnect 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);}
اسلاید 27: Programming TCP Client-Server in JavaIf you are programming a server, then this is how you open a socket: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.ServerSocket MyService;try {MyServerice = new ServerSocket(PortNumber); } catch (IOException e) { System.out.println(e); }Socket clientSocket = null;try {clientSocket = MyService.accept();}catch (IOException e) {System.out.println(e);}
اسلاید 28: Programming TCP Client-Server in JavaHow 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: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 fromthe client:DataInputStream input;try { input = new DataInputStream(MyClient.getInputStream());}catch (IOException e) { System.out.println(e);}DataInputStream input;try { input = new DataInputStream(clientSocket.getInputStream());}catch (IOException e) { System.out.println(e);}
اسلاید 29: Programming TCP Client-Server in JavaHow to create an output stream?On the client side, you can create an output stream to send informationto the server socket using the class PrintStream or DataOutputStreamof java.io:The class PrintStream has methods for displaying textual representationof Java primitive data types. Its write and println methods are important.Also, you may want to use the DataOutputStream:Many of its methods write a single Java primitive type to the output stream. The method writeBytes is a useful one.PrintStream output;try { output = new PrintStream(MyClient.getOutputStream());}catch (IOException e) { System.out.println(e);}DataOutputStream output;try { output = new DataOutputStream(MyClient.getOutputStream());}catch (IOException e) { System.out.println(e);}
اسلاید 30: Programming TCP Client-Server in JavaOn the server sideyou can use the class PrintStream to send information to the client.Note: You can use the class DataOutputStream as mentioned previously.PrintStream output;try { output = new PrintStream(clientSocket.getOutputStream());}catch (IOException e) { System.out.println(e);}
اسلاید 31: Programming TCP Client-Server in JavaHow to close sockets?You should always close the output and input stream before you close the socket.On the client side:On the server side:try { output.close(); input.close(); MyClient.close();}catch (IOException e) { System.out.println(e);}try { output.close(); input.close(); clientSocket.close(); MyService.close();}catch (IOException e) { System.out.println(e);}
اسلاید 32: Programming UDP Client-Server in JavaHow to open a datagram socket?If you are programming a client, then you would create an object of DatagramSocket classIf you are programming a server, then this is how you open a socket:try { DatagramSocket socket = new DatagramSocket();}catch (IOException e) { System.out.println(e);}DatagramSocket socket = null;try {socket = new DatagramSocket(4445);} catch (IOException e) { System.out.println(e); }
اسلاید 33: Programming UDP Client-Server in JavaHow to send/receive on Datagram sockets?On the client side, you can use the DatagramPacket classTo send dataTo receive databyte[] buf = new byte[256];InetAddress address = InetAddress.getByName(args[0]);DatagramPacket packet = new DatagramPacket(buf, buf.length, address, 4445);socket.send(packet);packet = new DatagramPacket(buf, buf.length);socket.receive(packet);String received = new String(packet.getData());System.out.println(“Received from server: + received);
اسلاید 34: Programming UDP Client-Server in JavaHow to send/receive on Datagram sockets?On the Server side, you can use the DatagramPacket classTo receive dataTo send dataHow to close a Datagram socket?byte[] buf = new byte[256];DatagramPacket packet = new DatagramPacket(buf, buf.length);socket.receive(packet);InetAddress address = packet.getAddress();int port = packet.getPort();packet = new DatagramPacket(buf, buf.length, address, port);socket.send(packet);socket.close();
اسلاید 35: ReferencesMan pages in LinuxAccesssible through following commandman 2 <system_call_name>E.g. man 2 socket“Unix network programming” by Richard StevensBeej’s guide to Network Programminghttp://beej.us/guide/bgnet/The Java Tutorial – Custom Networkinghttp://java.sun.com/docs/books/tutorial/networking/Lecture notes of cs423 from Dr. Bob Cotterhttp://www.sce.umkc.edu/~cotterr/cs423_fs05/cs423_fs05_lectures.html
نقد و بررسی ها
هیچ نظری برای این پاورپوینت نوشته نشده است.