Sockets Part 6

Download Report

Transcript Sockets Part 6

CS 471/571
Sockets Part 6
Quiz 6
• Same material as quiz 5 and the following
• Write small program segments using Java to
– Create a TCP server socket
– Create a datagram socket
– Create a connection to a TCP server socket
– Accept a TCP connection request
– Send/Receive a datagram packet
– Send/Receive bytes to a TCP socket
Web Server
• Implement a very simple Web Server that can
process GET requests
• Java
• C
HTTP request message: general format
method
sp
URL
header field name
sp
value
version
cr
cr
value
cr
request
line
header
lines
~
~
header field name
lf
lf
~
~
~
~
cr
lf
lf
entity body
Application Layer
~
~
body
2-4
HTTP response message: general format
version
sp Status code
header field name
sp value
sp phrase cr
cr
~
~
cr
~
~
cr
status
line
lf
header
lines
~
~
header field name sp value
lf
lf
lf
entity body
Application Layer
~
~
body
2-5
Simple Web Server in Java (from
previous version of Kurose and Ross)
import java.io.*;
import java.net.* ;
import java.util.* ;
public final class WebServer {
public static void main(String argv[]) throws Exception {
// Get the port number from the command line.
int port = (new Integer(argv[0])).intValue();
// Establish the listen socket.
ServerSocket socket = new ServerSocket(port);
// Process HTTP service requests in an infinite loop.
Simple Web Server (Java)
while (true) {
// Listen for a TCP connection request.
Socket connection = socket.accept();
// Construct an object to process the HTTP request message.
HttpRequest request = new HttpRequest(connection);
// Create a new thread to process the request.
Thread thread = new Thread(request);
// Start the thread.
thread.start();
}
}
}
Simple Web Server (Java)
import java.io.* ;
import java.net.* ;
import java.util.* ;
final class HttpRequest implements Runnable {
final static String CRLF = "\r\n";
Socket socket;
public HttpRequest(Socket socket) throws Exception {
this.socket = socket;
}
public void run() {
try {
processRequest();
} catch (Exception e) {
System.out.println(e);
}
}
Simple Web Server (Java)
private void processRequest() throws Exception {
// Get a reference to the socket's input and output streams.
InputStream is = socket.getInputStream();
DataOutputStream os = new DataOutputStream(socket.getOutputStream());
// Set up input stream filters.
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// Get the request line of the HTTP request message.
String requestLine = br.readLine();
// Extract the filename from the request line.
StringTokenizer tokens = new StringTokenizer(requestLine);
tokens.nextToken(); // skip over the method, which should be "GET"
String fileName = tokens.nextToken();
// Prepend a "." so that file request is within the current directory.
fileName = "." + fileName ;
Simple Web Server (Java)
// Open the requested file.
FileInputStream fis = null ;
boolean fileExists = true ;
try {
fis = new FileInputStream(fileName);
} catch (FileNotFoundException e) {
fileExists = false ;
}
// Construct the response message.
String statusLine = null;
String contentTypeLine = null;
String entityBody = null;
Simple Web Server (Java)
if (fileExists) {
statusLine = "HTTP/1.0 200 OK" + CRLF;
contentTypeLine = "Content-Type: " +
contentType(fileName) + CRLF;
} else {
statusLine = "HTTP/1.0 404 Not Found" + CRLF;
contentTypeLine = "Content-Type: text/html" + CRLF;
entityBody = "<HTML>" +
"<HEAD><TITLE>Not Found</TITLE></HEAD>" +
"<BODY>Not Found</BODY></HTML>";
}
// Send the status line.
os.writeBytes(statusLine);
// Send the content type line.
os.writeBytes(contentTypeLine);
// Send a blank line to indicate the end of the header lines.
os.writeBytes(CRLF);
Simple Web Server (Java)
// Send the entity body.
if (fileExists) {
sendBytes(fis, os);
fis.close();
} else {
os.writeBytes(entityBody) ;
}
// Close streams and socket.
os.close();
br.close();
socket.close();
}
Simple Web Server (Java)
private static void sendBytes(FileInputStream fis,
OutputStream os) throws Exception {
// Construct a 1K buffer to hold bytes on their way to the socket.
byte[] buffer = new byte[1024];
int bytes = 0;
// Copy requested file into the socket's output stream.
while ((bytes = fis.read(buffer)) != -1) {
os.write(buffer, 0, bytes);
}
}
Simple Web Server (Java)
private static String contentType(String fileName) {
if(fileName.endsWith(".htm") || fileName.endsWith(".html")) {
return "text/html";
}
if(fileName.endsWith(".ram") || fileName.endsWith(".ra")) {
return "audio/x-pn-realaudio";
}
return "application/octet-stream" ;
}
}
Simple Web Server ( C )
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <ctype.h>
#include <pthread.h>
int main(int argc, char *argv[]) {
int sockfd1, sockfd2;
struct sockaddr_in server;
struct sockaddr_in client;
unsigned int clen;
pthread_t t;
int *s;
Simple Web Server ( C )
sockfd1 = socket(AF_INET, SOCK_STREAM, 0);
memset(&server, 0, sizeof(struct sockaddr_in));
server.sin_family = AF_INET;
server.sin_addr.s_addr = htonl(INADDR_ANY);
server.sin_port = htons(12000);
bind(sockfd1, (struct sockaddr *) &server, sizeof(struct sockaddr_in));
listen(sockfd1, 5);
while (1) {
sockfd2 = accept(sockfd1, (struct sockaddr *) &client, &clen);
s = (int *) malloc(sizeof(int));
*s = sockfd2;
pthread_create(&t, NULL, processRequest, (void *) s);
}
}
Simple Web Server ( C )
void *processRequest(void *s) { //Only handles html case where file is found
int sock = *((int *) s);
char firstLine[1024];
char line[1024];
char delim[2] = " ”;
char filename[100];
char *status1 = "HTTP/1.0 200 OK\r\n";
char *content1 = "Content-Type: text/html\r\n\r\n”;
char *token;
readFirstLine(firstLine, sock);
token = strtok(firstLine, delim);
token = strtok(NULL, delim);
Simple Web Server ( C )
strcpy(filename, ".");
strcat(filename, token);
FILE *fp = fopen(filename, "r");
send(sock, status1, strlen(status1), 0);
send(sock, content1, strlen(content1), 0);
while (fgets(line, 1024, fp) != 0) {
send(sock, line, strlen(line), 0);
}
close(sock);
fclose(fp);
return NULL;
}
Simple Web Server ( C )
void readFirstLine(char firstLine[], int sock) {
int i = 0;
char c;
int len;
len = recv(sock, &c, 1, 0);
while (len == 1 && c != '\n') {
firstLine[i] = c;;
i++;
len = recv(sock, &c, 1, 0);
}
firstLine[i] = '\n';
firstLine[i+1] = '\0';
}
Simple Web Server ( C )