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.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: