Networks Sockets and Streams
TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23 finger79 http80 pop3110
Socket = server + port server = ports …65535 client Socket
The Java Socket Class
Java Socket Class server ports …65535 client Socket instance
Sockets create Streams server ports client 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
Socket constructor Socket (String host, int port) throws IOException –port must be by name or text IP address –port must be
java.net.Socket Constructor: Socket (String host, int port) Socket s = new Socket(“ 80); in = s.getInputStream(); int k = in.read(); anInputStream (returns bytes) returns 1st byte of web page s in 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(“ ”, 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” “ ”
SocketTest.java import 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 )
boolean more = true; while (more) { String str = is.readLine(); if (str == null) more = false; else System.out.println(str); } } (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( ) ) );