socket programming
play

Socket programming Goal: learn how to build client/server - PDF document

Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API socket 5: Socket Programming introduced in BSD4.1 UNIX, a host-local , application- 1981 created/owned , Sockets are


  1. Socket programming Goal: learn how to build client/server application that communicate using sockets Socket API socket 5: Socket Programming ❒ introduced in BSD4.1 UNIX, a host-local , application- 1981 created/owned , ❒ Sockets are explicitly OS-controlled interface created, used, released by (a “door”) into which applications application process can ❒ client/server paradigm Last Modified: both send and ❒ two types of transport receive messages to/from service via socket API: 2/10/2003 2:38:37 PM another (remote or ❍ unreliable datagram local) application process ❍ reliable, byte stream- oriented 2: Application Layer 2: Application Layer 1 2 Languages and Platforms Sockets Socket: a door between application process Socket API is available for many languages on and end-end-transport protocol (UCP or many platforms: TCP) ❒ C, Java, Perl, Python,… ❒ *nix, Windows,… controlled by controlled by process application Socket Programs written in any language and process application developer socket developer running on any platform can communicate socket kernel controlled by kernel controlled by with each other! buffers, operating operating buffers, internet system variables system variables Writing communicating programs in different languages is a good exercise host or host or server server 2: Application Layer 2: Application Layer 3 4 Socket Programming is Easy Decisions ❒ Create socket much like you open a file ❒ Before you go to write socket code, decide ❍ Do you want a TCP-style reliable, full duplex, ❒ Once open, you can read from it and write connection oriented channel? Or do you want a to it UDP-style, unreliable, message oriented ❒ Operating System hides most of the channel? details ❍ 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 contacted 2: Application Layer 2: Application Layer 5 6

  2. Pseudo code TCP client Socket programming with TCP Client must contact server ❒ When client creates socket: Create socket, connectSocket client TCP establishes ❒ server process must first connection to server TCP be running Do an active connect specifying the IP ❒ When contacted by client, ❒ server must have created server TCP creates new address and port number of server socket (door) that socket for server process to welcomes client’s contact Read and Write Data Into connectSocket to communicate with client ❍ Frees up incoming port Client contacts server by: Communicate with server ❍ allows server to talk with ❒ creating client-local TCP Close connectSocket multiple clients socket ❒ specifying IP address, port application viewpoint number of server process TCP provides reliable, in-order transfer of bytes (“pipe”) between client and server 2: Application Layer 2: Application Layer 7 8 Pseudo code TCP server Example: Java client (TCP) Create socket (doorbellSocket) import java.io.*; import java.net.*; Bind socket to a specific port where clients can class TCPClient { contact you public static void main(String argv[]) throws Exception Register with the kernel your willingness to listen { that on socket for client to contact you String sentence; Loop String modifiedSentence; Accept new connection (connectSocket) Create BufferedReader inFromUser = input stream Read and Write Data Into connectSocket to new BufferedReader(new InputStreamReader(System.in)); Create Communicate with client client socket, Socket clientSocket = new Socket("hostname", 6789); Close connectSocket connect to server End Loop Create DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream()); output stream Close doorbellSocket attached to socket 2: Application Layer 2: Application Layer 9 10 Example: Java client (TCP), cont. Example: Java server (TCP) import java.io.*; import java.net.*; Create BufferedReader inFromServer = class TCPServer { input stream new BufferedReader(new attached to socket InputStreamReader(clientSocket.getInputStream())); public static void main(String argv[]) throws Exception { String clientSentence; sentence = inFromUser.readLine(); String capitalizedSentence; Create Send line welcoming socket outToServer.writeBytes(sentence + '\n'); to server ServerSocket welcomeSocket = new ServerSocket(6789); at port 6789 Read line modifiedSentence = inFromServer.readLine(); while(true) { Wait, on welcoming from server socket for contact System.out.println ("FROM SERVER: " + modifiedSentence ); Socket connectionSocket = welcomeSocket.accept(); by client clientSocket.close(); BufferedReader inFromClient = Create input new BufferedReader(new stream, attached InputStreamReader(connectionSocket.getInputStream())); } to socket } 2: Application Layer 2: Application Layer 11 12

  3. Client/server socket interaction: TCP Example: Java server (TCP), cont (Java) Server (running on hostid ) Client Create output create socket, stream, attached port= x , for DataOutputStream outToClient = to socket incoming request: new DataOutputStream (connectionSocket.getOutputStream()); welcomeSocket = Read in line ServerSocket() clientSentence = inFromClient.readLine(); from socket TCP create socket, wait for incoming connection setup connect to hostid , port= x connection request capitalizedSentence = clientSentence.toUpperCase() + '\n'; clientSocket = connectionSocket = Socket() welcomeSocket.accept() Write out line outToClient.writeBytes(capitalizedSentence); to socket send request using } read request from clientSocket } connectionSocket } End of while loop, write reply to loop back and wait for connectionSocket read reply from another client connection clientSocket close close connectionSocket clientSocket 2: Application Layer 2: Application Layer 13 14 Example: C client (TCP) Example: C client (TCP), cont. Warning: Should check return codes of major functions!! Omitted for space here bzero((char *) &sin, sizeof(sin)); #include <sys/socket.h> sin.sin_family = AF_INET; #include <netinet/in.h> sin.sin_port = htons(6789r); bcopy(hp->h_addr, (char *) &sin.sin_addr, Int main(int argc, char **argv) { hp->h_length); int connectionSocket; Connect to server char sentence[MAX_LINE]; connect(connectSocket, char modifiedSentence[MAX_LINE]; (struct sockaddr *) &sin, sizeof(sin)) struct hostent *hp; fgets(sentence, MAXLINE, stdin); Create connectionSocket = socket (PF_INET, SOCK_STREAM,0); buff[MAXLINE-1] = '\0'; Send line client socket write(connectSocket, sentence, strlen(sentence)+1, 0); to server Resolve hostname /* translate host name into peer's IP address */ Read line read(connectionSocket, modifiedSentence, Of server to hp = gethostbyname(“hostname”); sizeof(modifiedSentence), 0); from server IP adresss fprintf(stderr, “FROM SERVER: %s \n“, modifiedSentence); close(connectSocket); 2: Application Layer 2: Application Layer 15 } 16 Example: C server (TCP) Example: C server (TCP), cont Warning: Should check return codes of major functions!! Omitted for space here for ( ; ; ) { Wait, on welcoming #include <sys/socket.h> #include <netinet/in.h> socket for contact connectionSocket = by client accept(welcomeSocket , (struct sockaddr *) NULL, NULL); Int main(int argc, char **argv) { Read in line int welcomeSocket, connectionSocket; from socket char clientSentence[MAX_LINE];; bytesRead = read(connectionSocket, clientSentence, MAXLINE); struct sockaddr_in servaddr; //would have to write the capitalize procedure welcomeSocket = socket(AF_INET, SOCK_STREAM, 0); capitalize(clientSentence); servaddr.sin_family = AF_INET; Write out line write(connectionSocket, clientSentence, MAXLINE); servaddr.sin_addr.s_addr = htonl(INADDR_ANY); to socket servaddr.sin_port = htons(6789); close(connectSocket); Create } welcoming socket bind(lwelcomeSocket, (struct sockaddr *) &servaddr, \ close(welcomeSocket); at port 6789 sizeof(servaddr)); } listen(welcomeSocket , LISTENQ); End of while loop, loop back and wait for another client connection 2: Application Layer 2: Application Layer 17 18

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend