Networks Sockets and Streams. TCP/IP in action server ports 13 17 80 …65535 lower port numbers...

Post on 04-Jan-2016

212 views 0 download

Transcript of Networks Sockets and Streams. TCP/IP in action server ports 13 17 80 …65535 lower port numbers...

Networks

Sockets and Streams

TCP/IP in action

server

ports

13 17 80 …65535

lower port numbers (1..1023) are reserved

portecho 7time 13ftp 20telnet 23finger 79http 80pop3 110

Socket = server + port

server = www.seas.smu.edu

ports

13 17 80 …65535

client

Sockethttp://www.seas.smu.edu

The Java Socket Class

Java Socket Class

server

ports

13 17 3180 …65535

client

Socket instance

Sockets create Streams

server

ports

13 17 3180client

Socket instance

InputStream

OutputStream

class Socket• Socket is the Java representation of a TCP

network connection• Using Socket, a client can create a stream-based

communication channel with a remote host• To communicate, a socket connection to the

remote host must be established - specifying the address and the port

• There must be a server program actively listening on the port or the connection will fail -- throw an Exception

Socketconstructor

• Socket (String host, int port) throws IOException– port must be by name or text IP

address– port must be 1-65535

java.net.Socket• Constructor:

Socket (String host, int port)

Socket s = new Socket(“www.sun.com”, 80);

in = s.getInputStream();int k = in.read();

anInputStream(returns bytes)

returns 1st byte of web page

sin

world of TCP/IP

Socket methods• Socket (String host, int port)

– constructor

• InputStream getInputStream ()– gets InputStream for reading

• OutputStream getOutputStream()– get OutputStream for writing

java.net.Socket• Constructor:

Socket (String host, int port)

Socket s = new Socket(“112.62.12.0”, 80);

s

in

world of TCP/IP

out

can use IP address written as a string

the socket instance acts as a stream “factory” -- design pattern

more Socket methods

• synchronized void close ()– closes the socket

• void setSoTimeout (int timeout)– Socket will block for only this amt of time

-- then InterruptedException is raised

“localhost”

“127.0.0.1”

SocketTest.javaimport java.io.*;import java.net.*;

class SocketTest{ public static void main(String[ ] args) { try { Socket t =

new Socket(”nova.seas.smu.edu", 13); BufferedReader is = new BufferedReader (new InputStreamReader(t.getInputStream()));

(Continued ) (Continued )

boolean more = true; while (more) { String str = is.readLine(); if (str == null) more = false; else System.out.println(str); } }

(Continued ) (Continued )

catch(IOException e) { System.out.println("Error" + e); } }}

Socket t = new Socket(”nova.seas.smu.edu", 13); BufferedReader is = new BufferedReader (new InputStreamReader( t.getInputStream( ) ) );