date | lab | lecture |
13 Jan | - | Lecture 1 |
20 Jan | Lab 1 | Lecture 2 |
27 Jan | Lab 2 | Lecture 3 |
3 Feb | Lab 3 | Lecture 4 |
10 Feb | Lab 4 | Lecture 5 |
17 Feb | Reading | Week |
24 Feb | Lab 5 | Lecture 6 |
3 March | Lab 6 | Lecture 7 |
10 March | Lab 7 | Lecture 8 |
17 March | Lab 8 | Lecture 9 |
24 March | Lab 9 | Lecture 10 |
28 April | Lab 10 |
The course is assessed by coursework(20%) and exam (80%).
A zip file containing all a zip file which contains all the source code and a README file (instructions on how to run program) should be uploaded. to
IS52025A-assignments-2013-14/cwk12014/
This course has two assignements. One to implement an Internet chat room and the other is to implement a web-crawler which creates a graph of a particular domain (not assessed).
You must implement an Internet chat room with the following components:
This chat client has two windows, one for typing in messages and commands and another for receiving messages from users. There are the following commands:
This is the initial request to join the chatroom with particular username.
This sends a message only to the user called `user'.
This displays all online users.
This closes the client gracefully.
You should make sure your client and server programs do not crash.
Some useful code done in class:
class firstPart { class Message { int messageType; String username; String message; Message(int i, String m, String u ) { messageType=i; username=u; message=m; } } static String fp (String s) { String result=""; for (int i=0;i<s.length();i++) { if (s.charAt(i)==' ') return result; else result=result+s.charAt(i); } return result; } static Message parseMessage(String s) { if ((fp(s).equals("!join")) return new Message(0,"",secondPart(s)); else if (s.equals("!block")) return new Message(4,"",""); else etc. etc. } public static void main(String [] args) { System.out.println(fp(args[0])); if (fp(args[0]).equals("!join")) System.out.println("WHOOOPEEEE!"); } }
Deadline Midnight 28 April 2014.
Coursework One:
A zip file containing all a zip file which contains all the source code and a README file (instructions on how to run program) should be uploaded to
IS52025A-assignments-2013-14/cwk12014/on igor.
Coursework Two:
A zip file containing all a zip file which contains all the source code and a README file (instructions on how to run program) should be uploaded. to
IS52025A-assignments-2013-14/cwk22014/on igor.
Watch Clients and Servers video
import java.io.*; import java.net.*; class evenSimplerEchoServer { public static void main(String[] argv) throws Exception {ServerSocket s = new ServerSocket(5000); Socket t = s.accept();//wait for client to connect InputStream b = t.getInputStream(); OutputStream p =t.getOutputStream(); int c; while((c=b.read())!=-1) { p.write(c); p.flush(); System.out.print((char) c); } } }
import java.io.*; import java.net.*; class evenSimplerEchoClient { public static void main(String[] argv) throws Exception {Socket s = new Socket("localhost",5000); OutputStream p =s.getOutputStream(); InputStream i = s.getInputStream(); InputStreamReader b = new InputStreamReader(System.in); int c; while((c=b.read())!=-1) { p.write(c); p.flush(); System.out.print((char)i.read()); } } }
Compile and run thread below:
class threads { static class t1 extends Thread { public void run() { int i=0; while(true) { System.out.println("hello"+i++); } } } static class t2 extends Thread { public void run() { int i=0; while(true) { System.out.println("goodbye"+i++); } } } public static void main( String [] args) { new t1().start(); new t2().start(); } }
Run it a few times. What happens? Is it the same each time?
import java.awt.*; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; public class evenSimplerGuiClient implements ActionListener { private JTextField user = new JTextField("user",20); private JTextArea server = new JTextArea("server",5,20); private JScrollPane sp =new JScrollPane(server); private Socket s; private OutputStreamWriter p; private InputStream i; private JFrame window = new JFrame("client"); class serverReader extends Thread { public void run() { String s=""; int c; try { while ((c=i.read())!=-1) { s=s+ ((char)c); server.setText(s); } } catch(Exception e){}; } } public evenSimplerGuiClient() throws Exception { try { s = new Socket("localhost",5000); p =new OutputStreamWriter(s.getOutputStream()); i = s.getInputStream(); new serverReader().start(); } catch (Exception e){System.out.println("error");}; window.setSize(300,300); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); window.setLayout(new FlowLayout()); window.add(sp); window.add(user); user.addActionListener(this); window.setVisible(true); } public void actionPerformed(ActionEvent a) { String s= user.getText(); try { p.write(s+'\n',0,s.length()+1); p.flush();user.setText(""); } catch (Exception e){}; } public static void main(String[] args) throws Exception { new evenSimplerGuiClient(); } }
import java.io.*; import java.net.*; class simpleMultiThreadedEchoServer { public static void main(String[] argv) throws Exception { ServerSocket s = new ServerSocket(5000); Transaction k; while (true) { k = new Transaction(s.accept()); k.start(); } } } class Transaction extends Thread { InputStream b; OutputStream p; public Transaction(Socket s) throws Exception { b=s.getInputStream(); p =s.getOutputStream(); } public void run() { int c; try { while((c=b.read())!=-1) { p.write((char)c); p.flush(); System.out.print((char)c); } } catch (Exception e) { } } }
See My blog
Suppose you have a server called fred.bloggs.ac.uk at your institution and you have written some nice server which is listening on port 9999 and suddenly in the middle of your course port 9999 gets blocked. What do you do?
Luckily you can SSH onto fred.blogs.ac.uk
(1) Run you server as normal on fred.blogs.ac.uk listening on port 9999.
(2) then type: ssh -L4950:fred.bloggs.ac.uk:9999 fred.bloggs.ac.uk
(You will need your username if your username on your local machine is different form your username on fred.bloggs. too like this:
ssh -L4950:fred.bloggs.ac.uk:9999 mas01sd@fred.bloggs.ac.uk)
(3) finally point your clients at your local machine port 4950 and off you go!
2. before connecting, open Connection-SSH-Tunnels
3 enter local port in "Source port" (4950)
4. enter remote host:port in destination (igor.gold.ac.uk:9999)
5 click Add then the tunnel shows in the list box above
6. Click Open ( you get a spurious connection to igor which you just minimize and ignore - thats the tunnel)
Watch Bypassing Firewalls Using SSH Tunnelling
and install FoxyProxy on your browser and
and configure FoxyProxy to use localhost:7335 for all your urls
This is useful if, say you are abroad, and you want to use things only available in the UK.
Watch SSH tunnelling and Foxyproxy
Watch Video about The need for synchronization with shared data and threads in Java
lass test0 { static int a=0; static class t1 extends Thread { public void run() { for (int i=0;i<100000;i++) {a++;} System.out.println(a); } } static class t2 extends Thread { public void run() { for (int i=0;i<100000;i++) {a++;} System.out.println(a); } } public static void main(String [] args) { new t1().start(); new t2().start(); } }We have two thread both updating the shared variable a. What should the final value of a be. 200000. But is it? Why not?
class test1 { static int a=0; static void update() { a++; } static class t1 extends Thread { public void run() { for (int i=0;i<100000;i++) {update();} System.out.println(a); } } static class t2 extends Thread { public void run() { for (int i=0;i<100000;i++) {update();} System.out.println(a); } } public static void main(String [] args) { new t1().start(); new t2().start(); } }same problem!
class test1 { static int a=0; static synchronized void update() { a++; } static class t1 extends Thread { public void run() { for (int i=0;i<100000;i++) {update();} System.out.println(a); } } static class t2 extends Thread { public void run() { for (int i=0;i<100000;i++) {update();} System.out.println(a); } } public static void main(String [] args) { new t1().start(); new t2().start(); } }Problem solved!
Try:
class Friend { String name; public Friend(String name) { this.name = name; } public /*synchronized*/ void bow(Friend f) { System.out.println(name); f.bowBack(); } public /*synchronized */void bowBack() { System.out.println(name); } } class bla extends Thread { Friend one,two; bla(Friend f, Friend g) { one=f; two=g; } public void run() { one.bow(two);} } public class Deadlock { public static void main(String[] args) { Friend fred = new Friend("Fred"); Friend jack = new Friend("Jack"); new bla(fred,jack).start(); new bla(jack,fred).start(); } }Now uncomment the
synchronized
labels and describe what happens. Why?
import java.util.*; import java.io.*; import java.net.*; class SynchList { ArrayList <OutputStream> it; SynchList() { it=new ArrayList <OutputStream> (); } synchronized OutputStream get(int i) { return it.get(i); } synchronized void add(OutputStream o) { it.add(o); } synchronized int size() { return it.size(); } } class broadcasterWithList { static SynchList Outputs= new SynchList(); static int i=0; public static void main(String[] argv) throws Exception {ServerSocket s = new ServerSocket(5000); Transaction k; while (true) {k = new Transaction(i,s.accept(),Outputs);k.start();i++; System.out.println("client joined");}//wait for client to connect } } class Transaction extends Thread { SynchList outputs; int n; Socket t; InputStream b; OutputStream p; public Transaction(int i,Socket s, SynchList v) throws Exception { outputs=v; n=i;t=s; b = t.getInputStream(); p =t.getOutputStream(); outputs.add(p); } public void run() { int c; try{ while((c=b.read())!=-1) { for (int j=0;j<outputs.size();j++) { //if (j!=n) { (outputs.get(j)).write(c); (outputs.get(j)).flush(); } } System.out.print((char)c); System.out.print("size of ArrayList :"+outputs.size()); } System.out.print("left loop"); } catch (Exception e) { System.out.print(e);} } }
test1
above. This program must contain two threads a
and b
.
Thread a
must call method f
.
Thread b
must call method g
.
Methods f
and g
must both contain infinite loops one printing out hello, the other goodbye. What is the difference when f
and g
are synchronized and not synchronized? What is this an example of? (answer - starvation)
Watch Broadcaster server which removes dead clients from its list.
import java.util.*; import java.io.*; import java.net.*; class SynchList { ArrayList <PrintStream> it; SynchList() { it=new ArrayList <PrintStream> (); } synchronized PrintStream get(int i) { return it.get(i); } synchronized void add(PrintStream o) { it.add(o); } synchronized int size() { return it.size(); } synchronized void remove(PrintStream o) { it.remove(o); } } class StringBroadcaster { static SynchList Outputs= new SynchList(); static int i=0; public static void main(String[] argv) throws Exception {ServerSocket s = new ServerSocket(5000); Transaction k; while (true) {k = new Transaction(Outputs.size(),s.accept(),Outputs);k.start(); System.out.println("client joined");}//wait for client to connect } } class Transaction extends Thread { SynchList outputs; int n; Socket t; InputStream b; OutputStream p; PrintStream pp; public Transaction(int i,Socket s, SynchList v) throws Exception { outputs=v; n=i;t=s; b = t.getInputStream(); p =t.getOutputStream(); pp =new PrintStream(p); outputs.add(pp); } public void run() { Scanner s= new Scanner(b); int c; try{ while(s.hasNext()) { String it=s.next(); for (int j=0;j<outputs.size();j++) { //if (j!=n) { (outputs.get(j)).println(n+":"+it); (outputs.get(j)).flush(); } } System.out.println(it); // System.out.print("size of ArrayList :"+outputs.size()); } System.out.print("client " + n + " left loop"); outputs.remove(pp); } catch (Exception e) { outputs.remove(pp);System.out.print(e);} } }
import java.io.*; public class Student implements Serializable { String name; int mark; public Student (String n, int a) { mark=a;name=n; } public String toString() { return name+" "+age; } } class objectClient1 { public static void main(String[] argv) throws Exception {Socket s = new Socket("localhost",5000); ObjectOutputStream p =new ObjectOutputStream(s.getOutputStream()); ObjectInputStream q =new ObjectInputStream(s.getInputStream()); Scanner b = new Scanner(System.in); int c; while(b.hasNext()) { String name=b.nextLine(); int mark=Integer.parseInt(b.nextLine()); p.writeObject(new Student(name,mark)); p.flush(); System.out.println(q.readObject()); } } }
import java.io.*; import java.net.*; class objectEchoServer { public static void main(String[] argv) throws Exception {ServerSocket s = new ServerSocket(5000); Socket t = s.accept();//wait for client to connect System.out.println("server connected"); ObjectInputStream b = new ObjectInputStream(t.getInputStream()); ObjectOutputStream q = new ObjectOutputStream(t.getOutputStream()); Object c; while((c=b.readObject())!=null) { q.writeObject(c); } } }
objectClient1
above.
answer (almost)
Student
Object whose name
is `end' and whose mark is 0.
import java.sql.*; public class seb6 { public static void main(String[] args) throws Exception { Class.forName("com.mysql.jdbc.Driver"); Connection connect= DriverManager.getConnection("jdbc:mysql://localhost/silly","mas01sd","seb"); Statement st = connect.createStatement(); // st.executeUpdate("INSERT INTO one VALUES('" + args[0] +"','" + args[1] + "');"); ResultSet resultSet = st.executeQuery("SELECT * from authors"); while (resultSet.next()) { for (int i=1;i<4;i++)System.out.print(resultSet.getString(i) + " "); System.out.println(); } } }
Watch Video about accessing Databases in Java.
Watch Video about Tunnelling though the firewall to access your database server.
import java.sql.*; public class seb7 { public static void main(String[] args) throws Exception { Class.forName("org.postgresql.Driver"); Connection connect= DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5001/mas01sd","mas01sd",""); Statement st = connect.createStatement(); // st.executeUpdate("INSERT INTO one VALUES('" + args[0] +"','" + args[1] + "');"); ResultSet resultSet = st.executeQuery("SELECT * from weather"); while (resultSet.next()) { for (int i=1;i<4;i++)System.out.print(resultSet.getString(i) + " "); System.out.println(); } } }
Watch Video about accessing Postgres Database Server in Java.
import java.sql.*; import java.io.Console; public class seb8 { public static void main(String[] args) throws Exception { Class.forName("org.postgresql.Driver"); Console cons; char[] passwd; String pass=""; if ((cons = System.console()) != null && (passwd = cons.readPassword("%s", "Password:")) != null) { for (int i=0;i<passwd.length;i++) pass+=passwd[i]; } Connection connect= DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5001/mas01sd","mas01sd",pass); Statement st = connect.createStatement(); // st.executeUpdate("INSERT INTO one VALUES('" + args[0] +"','" + args[1] + "');"); ResultSet resultSet = st.executeQuery("SELECT * from weather"); while (resultSet.next()) { for (int i=1;i<4;i++)System.out.print(resultSet.getString(i) + " "); System.out.println(); } } }
javac -cp .:mysql-connector-java-5.0.8-bin.jar seb5.java
and to run:
For example:
java -cp .:mysql-connector-java-5.0.8-bin.jar seb5
if (x instanceOf Student) ...
for this.)
import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; public class SebLinks { public static void main(String[] args) throws IOException { String url = args[0]; Document doc = Jsoup.connect(url).get(); Elements links = doc.select("a[href]"); for (Element link : links) System.out.println(link.attr("abs:href")); } }
import java.util.ArrayList; import java.util.HashSet; import java.util.HashSet.*; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; public class NewSpider1 { static HashSet<String> links (String url) { HashSet<String> a= new HashSet<String>(); try{org.jsoup.Connection z=Jsoup.connect(url); Document doc = z.get(); Elements links = doc.select("a[href]"); for (Element link : links) a.add(link.attr("abs:href")); } catch (Exception e) { } return a; } static void Spider (String url, int n) { HashSet<String> alreadyVisited = new HashSet <String> (); HashSet<String> toVisit = new HashSet <String> (); toVisit.addAll(links(url)); alreadyVisited.add(url); int i=0; while (i<n && !toVisit.isEmpty()) { String z= toVisit.iterator().next(); boolean already=alreadyVisited.contains(z); if (already) toVisit.remove(z); else { System.out.println(z); HashSet <String> k= links(z); toVisit.addAll(k); alreadyVisited.add(z); i++; } } } public static void main(String[] args) throws IOException { String url = args[0]; Spider(url,Integer.parseInt(args[1])); } }
javac -cp jsoup-1.6.1.jar SebLinks.java
To run do
java -cp .:jsoup-1.6.1.jar SebLinks http://localhost(or something else apart from
http://localhost
.)
import java.util.ArrayList; import java.util.HashSet; import java.util.HashSet.*; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; public class NewSpider2 { tatic HashSet<String> links (String url) { HashSet<String> a= new HashSet<String>(); try{org.jsoup.Connection z=Jsoup.connect(url); Document doc = z.get(); Elements links = doc.select("a[href]"); for (Element link : links) a.add(link.attr("abs:href")); } catch (Exception e) { } return a; } static void Spider (String url, int n, String contains) { HashSet<String> alreadyVisited = new HashSet <String> (); HashSet<String> toVisit = new HashSet <String> (); toVisit.addAll(links(url)); alreadyVisited.add(url); int i=0; while (i<n && !toVisit.isEmpty()) { String z= toVisit.iterator().next(); boolean already=alreadyVisited.contains(z); if (already) toVisit.remove(z); else { if (z.contains(contains)) { System.out.println(z); HashSet <String> k= links(z); toVisit.addAll(k); } alreadyVisited.add(z); i++; } } } public static void main(String[] args) throws IOException { String url = args[0]; Spider(url,100,args[1]); } }
mport java.util.ArrayList; import java.util.HashSet; import java.util.HashSet.*; import org.jsoup.Jsoup; import org.jsoup.nodes.Document; import org.jsoup.nodes.Element; import org.jsoup.select.Elements; import java.io.IOException; public class Brokens { static boolean broken(String url) { try {Jsoup.connect(url).get(); return false;} catch (java.net.MalformedURLException e) {return true;} catch (IOException e){if (e.toString().contains("java.io.IOException: 404")) return true; return false; //this means it exists but isn't html } catch(Exception e) { return false; //for any other errror assume not broken - this is a guess } } static HashSet<String> links (String url) { HashSet<String> a= new HashSet<String>(); try{org.jsoup.Connection z=Jsoup.connect(url); Document doc = z.get(); Elements links = doc.select("a[href]"); for (Element link : links) a.add(link.attr("abs:href")); } catch (Exception e) { } return a; } static void Spider (String url, int n, String contains) { HashSet<String> alreadyVisited = new HashSet <String> (); HashSet<String> toVisit = new HashSet <String> (); toVisit.addAll(links(url)); alreadyVisited.add(url); int i=0; while (i<n && !toVisit.isEmpty()) { String z= toVisit.iterator().next(); boolean already=alreadyVisited.contains(z); if (already) toVisit.remove(z); else { if (z.contains(contains)) { System.out.println(z); HashSet <String> k= links(z); toVisit.addAll(k); } alreadyVisited.add(z); i++; } } for (String k:alreadyVisited) if (broken(k)) System.out.println("Broken: " +k); } public static void main(String[] args) throws IOException { String url = args[0]; Spider(url,100,args[1]); } }