TCP sockets programming

Here you can find a copy of the source code java files I wrote during last class.

This is the client.

import java.net.Socket;
import java.io.*;
import java.util.Scanner;

class TestTCP {
public static void main(String args[]) throws java.net.UnknownHostException, java.io.IOException , java.lang.InterruptedException{
Socket s = new Socket ( "www.upv.es", 80 );
// Thread.sleep(100000);
PrintWriter output = new PrintWriter( s.getOutputStream(), true);
output.println("GET / HTTP/1.0");
output.println("");
Scanner input = new Scanner( s.getInputStream());
while(true) System.out.println(input.nextLine());
}
}


And this is the server code:

import java.net.*;
import java.io.*;
import java.util.Scanner;

class Server {

public static void main(String args[]) throws IOException, InterruptedException{
ServerSocket ss = new ServerSocket(8080);
while(true) {
Socket s = ss.accept();
Scanner input = new Scanner( s.getInputStream());
PrintWriter output = new PrintWriter( s.getOutputStream(), true);
System.out.println(input.nextLine()); // reads a line from the socket (client)
output.println("Hello client!");
s.close();
}
}
}



Please note that I detailed during the class some DOs and DON'Ts that not necessarily show in my (quick and dirty) code.

No comments: