Java Networking -- Socket Server socket class: ServerSocket wait for requests from clients. after a request is received, a client socket is generated.

Slides:



Advertisements
Similar presentations
CS Network Programming CS 3331 Fall CS 3331 Outline Socket programming Remote method invocation (RMI)
Advertisements

Socket Programming ENTERPRISE JAVA. 2 Content  Sockets  Streams  Threads  Readings.
Using TCP sockets in Java Created by M Bateman, A Ruddle & C Allison As part of the TCP View project.
Referring to Java API Specifications
Socket Programming By Ratnakar Kamath. What Is a Socket? Server has a socket bound to a specific port number. Client makes a connection request. Server.
School of Information Technologies Multithreading NETS3303/3603 Week 3.
9. Exceptions An exception occurs when our code asks the JVM to perform the technically impossible and unanticipated (by the compiler)! Under these circumstances,
Lecture 10: Networking using Socket Programming. Client-Server Model b The term server applies to any program that offers a service that can be reached.
Network Read/Write. Review of Streams and Files java.io package InputStream and OutputStream classes for binary bytes Reader and Writer classes for characters.
COMP201 Java Programming Part III: Advanced Features Topic 14: Networking Volume II,Chapter 3.
Java Threads A tool for concurrency. OS schedules processes Ready Running 200 Blocked A process loses the CPU and another.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Programming Applets How do Applets work ? This is an HTML page This is the applet’s code It has a link to an applet.
System Programming Practical session 10 Java sockets.
CIS – Spring Instructors: Geoffrey Fox, Bryan Carpenter Computational Science and.
Java sockets. From waiting.
System Programming Practical session 11 Multiple clients server Non-Blocking I/O.
Client/Server In Java An Introduction to TCP/IP and Sockets.
Projekt współfinansowany przez Unię Europejską w ramach Europejskiego Funduszu Społecznego „Networking”
Socket Communication Sockets provide an abstraction of two-point communication The two sides only read/write without concern for how data is translated.
1 Fall 2005 Socket Programming Qutaibah Malluhi Computer Science and Engineering Qatar University.
CSE 341, S. Tanimoto Java networking- 1 Java Networking Motivation Network Layers Using Sockets A Tiny Server Applets URLs Downloading Images, MediaTracker.
Io package as Java’s basic I/O system continue’d.
CS4273: Distributed System Technologies and Programming I Lecture 5: Java Socket Programming.
Ryerson University CPS Distributing Computing with Java.
CSCE 515: Computer Network Programming Chin-Tser Huang University of South Carolina.
Cli/Serv.: Chat/121 Client/Server Distributed Systems v Objectives –discuss a client/server based chat system –mention two other ways of chatting.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
Chapter 9 1 Chapter 9 – Part 1 l Overview of Streams and File I/O l Text File I/O l Binary File I/O l File Objects and File Names Streams and File I/O.
Practicum: - Client-Server Computing in Java Fundamental Data Structures and Algorithms Margaret Reid-Miller 13 April 2004.
Object Oriented Programming in Java Lecture 16. Networking in Java Concepts Technicalities in java.
© Amir Kirsh Java Networking Written by Amir Kirsh.
Lecture 9 Network programming. Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on the Internet.
Li Tak Sing COMPS311F. Case study: consumers and producers A fixed size buffer which can hold at most certain integers. A number of producers which generate.
Lab 2C Primer I/O in Java Sockets Threads More Java Stuffs.
1 Network Programming and Java Sockets. 2 Network Request Result a client, a server, and network Client Server Client machine Server machine Elements.
Web Design & Development 1 Lec - 21 Umair Javed. Web Design & Development 2 Socket Programming.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae, VUW Networking COMP # 22.
Networks Sockets and Streams. TCP/IP in action server ports …65535 lower port numbers ( ) are reserved port echo7 time13 ftp20 telnet23.
 2003 Joel C. Adams. All Rights Reserved. Calvin CollegeDept of Computer Science(1/11) Java Sockets and Simple Networking Joel Adams and Jeremy Frens.
1 cs205: engineering software university of virginia fall 2006 Network Programming* * Just enough to make you dangerous Bill Cheswick’s map of the Internet.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Java Socket Programming.
VII. Sockets. 1. What is a Socket? A socket is one end-point of a two-way communication link between two programs running on the network. Socket classes.
Java Server Programming Web Interface for Java Programs.
Part 4: Network Applications Client-server interaction, example applications.
By Vivek Dimri. Basic Concepts on Networking IP Address – Protocol – Ports – The Client/Server Paradigm – Sockets The Java Networking Package – The InetAddress.
TCP/IP Protocol Stack IP Device Drivers TCPUDP Application Sockets (Gate to network) TCP: –Establish connection –Maintain connection during the communication.
UNIT-6. Basics of Networking TCP/IP Sockets Simple Client Server program Multiple clients Sending file from Server to Client Parallel search server.
Java Programming II Java Network (I) Java Programming II.
1 Lecture 9: Network programming. 2 Manipulating URLs URL is an acronym for Uniform Resource Locator and is a reference (an address) to a resource on.
Java Server Sockets ServerSocket : Object to listen for client connection requests Throws IOException accept() method to take the client connection. Returns.
CS390- Unix Programming Environment CS 390 Unix Programming Environment Topics to be covered: Java Packages Thread Example Java Socket Programming.
MT311 Java Application Development and Programming Languages Li Tak Sing ( 李德成 )
Network Programming: Servers. Agenda l Steps for creating a server Create a ServerSocket object Create a Socket object from ServerSocket Create an input.
Spring/2002 Distributed Software Engineering C:\unocourses\4350\slides\DefiningThreads 1 Java API for distributed computing.
Li Tak Sing COMPS311F. Case study: a multithreaded chat server The source contains 3 files: ChatServer //the chat server ChatThread //the thread on the.
School of Engineering and Computer Science Victoria University of Wellington Copyright: Peter Andreae david streader, VUW Echo Networking COMP
CS 5204 Fall 00 1 Distributed Programming low level: sending data among distributed computations higher level: supporting invocations among distributed.
Java 13. Networking public class SumTest {
Stock Market Quotes – Socket Version
Echo Networking COMP
Threads in Java Two ways to start a thread
CSE 341, S. Tanimoto Java networking-
Block 15 Developing the Calculator application
Client-server Programming
PRESENTED To: Sir Abid………. PRESENTED BY: Insharah khan………. SUBJECT:
„Networking”.
Distributed Computing
Presentation transcript:

Java Networking -- Socket Server socket class: ServerSocket wait for requests from clients. after a request is received, a client socket is generated. Client socket class: Socket an endpoint for communication between two apps/applets. obtained by contacting a server generated by the server socket Communication is handled by input/output streams. Socket provides an input and an output stream.

A Simple Echo Server import java.io.*; import java.net.*; public class EchoServer { public static void main(String[] args) { try { ServerSocket s = new ServerSocket(8008); while (true) { Socket incoming = s.accept(); BufferedReader in = new BufferedReader( new InputStreamReader( incoming.getInputStream())); PrintWriter out = new PrintWriter( new OutputStreamWriter( incoming.getOutputStream()));

A Simple Echo Server (cont'd) out.println("Hello!...."); out.println("Enter BYE to exit."); out.flush(); while (true) { String str = in.readLine(); if (str == null) { break; // client closed connection } else { out.println("Echo: " + str); out.flush(); if (str.trim().equals("BYE")) break; } incoming.close(); } } catch (Exception e) {} }

Test the EchoServer with Telnet Use telnet as a client. venus% telnet saturn 8008 Trying Connected to saturn. Escape character is '^]'. Hello! This is the Java EchoServer. Enter BYE to exit. Hi, this is from venus Echo: Hi, this is from venus BYE Echo: BYE Connection closed by foreign host.

A Simple Client import java.io.*; import java.net.*; public class EchoClient { public static void main(String[] args) { try { String host; if (args.length > 0) { host = args[0]; } else { host = "localhost"; } Socket socket = new Socket(host, 8008);

A Simple Client (cont'd) (class EchoClient continued.) BufferedReader in = new BufferedReader( new InputStreamReader( socket.getInputStream())); PrintWriter out = new PrintWriter( new OutputStreamWriter( socket.getOutputStream())); // send data to the server for (int i = 1; i <= 10; i++) { System.out.println("Sending: line " + i); out.println("line " + i); out.flush(); } out.println("BYE"); out.flush();

A Simple Client (cont'd) (class EchoClient continued.) // receive data from the server while (true) { String str = in.readLine(); if (str == null) { break; } else { System.out.println(str); } } catch (Exception e) {} }

Multi-Threaded Echo Server To handle multiple requests simultaneously. In the main() method, spawn a thread for each request. public class MultiEchoServer { public static void main(String[] args) { try { ServerSocket s = new ServerSocket(8009); while (true) { Socket incoming = s.accept(); new ClientHandler(incoming).start(); } } catch (Exception e) {} }

Client Handler public class ClientHandler extends Thread { protected Socket incoming; public ClientHandler(Socket incoming) { this.incoming = incoming; } public void run() { try { BufferedReader in = new BufferedReader( new InputStreamReader( incoming.getInputStream())); PrintWriter out = new PrintWriter( new OutputStreamWriter( incoming.getOutputStream()));

Client Handler (cont'd) out.println("Hello!..."); out.println("Enter BYE to exit."); out.flush(); while (true) { String str = in.readLine(); if (str == null) { break; } else { out.println("Echo: " + str); out.flush(); if (str.trim().equals("BYE")) break; } incoming.close(); } catch (Exception e) {} }

Visitor Counter A server and an applet. The server keeps the visitor count in a file, and sends the count to clients when requested. No need for spawning thread, since only need to transmit an integer. Read and write files.

Visitor Counter Server public class CounterServer { public static void main(String[] args) { System.out.println("CounterServer started."); int i = 1; try { // read count from the file InputStream fin = new FileInputStream("Counter.dat"); DataInputStream din = new DataInputStream(fin); i = din.readInt() + 1; din.close(); } catch (IOException e) {}

Visitor Counter Server (cont'd) (class CountServer continued.) try { ServerSocket s = new ServerSocket(8190); while (true) { Socket incoming = s.accept(); DataOutputStream out = new DataOutputStream( incoming.getOutputStream()); System.out.println("Count: " + i); out.writeInt(i); incoming.close();

Visitor Counter Server (cont'd) (class CountServer continued.) OutputStream fout = new FileOutputStream("Counter.dat"); DataOutputStream dout = new DataOutputStream(fout); dout.writeInt(i); dout.close(); out.close(); i++; } } catch (Exception e) {} System.out.println("CounterServer stopped."); }

Counter Applet public class Counter extends Applet { protected int count = 0; protected Font font = new Font("Serif", Font.BOLD, 24); public void init() { URL url = getDocumentBase(); try { Socket t = new Socket(url.getHost(), 8190); DataInputStream in = new DataInputStream(t.getInputStream()); count = in.readInt(); } catch (Exception e) {} }

Counter Applet (cont'd) (class CountServer continued.) public void paint(Graphics g) { int x = 0, y = font.getSize(); g.setColor(Color.green); g.setFont(font); g.drawString("You are visitor: " + count, x, y); }

Broadcast Echo Server To handle multiple requests simultaneously. Broadcast messages received from any client to all active clients. Need to keep track of all active clients.

Broadcast Echo Server (cont'd) public class BroadcastEchoServer { static protected Set activeClients = new HashSet(); public static void main(String[] args) { int i = 1; try { ServerSocket s = new ServerSocket(8010); while (true) { Socket incoming = s.accept(); BroadcastClientHandler newClient = new BroadcastClientHandler(incoming, i++); activeClients.add(newClient); newClient.start(); } } catch (Exception e) {} }

Broadcast Client Handler public class BroadcastClientHandler extends Thread { protected Socket incoming; protected int id; protected BufferedReader in; protected PrintWriter out; public synchronized void sendMessage(String msg) { if (out != null) { out.println(msg); out.flush(); }

Broadcast Client Handler (cont'd) public BroadcastClientHandler(Socket incoming, int id) { this.incoming = incoming; this.id = id; try { if (incoming != null) { in = new BufferedReader( new InputStreamReader( incoming.getInputStream())); out = new PrintWriter( new OutputStreamWriter( incoming.getOutputStream())); } } catch (Exception e) {} }

Broadcast Client Handler (cont'd) public void run() { if (in != null && out != null) { sendMessage("Hello!..."); sendMessage("Enter BYE to exit."); try { while (true) { String str = in.readLine(); if (str == null) { break; } else { // echo back to this client sendMessage("Echo: " + str ); if (str.trim().equals("BYE")) { break; } else {

Broadcast Client Handler (cont'd) // broadcast to other active clients Iterator iter = BroadcastEchoServer.activeClients.iterator(); while (iter.hasNext()) { BroadcastClientHandler t = (BroadcastClientHandler) iter.next(); if (t != this) t.sendMessage("Broadcast(" + id + "): " + str); }}}} incoming.close(); // this client is no longer active BroadcastEchoServer.activeClients.remove(this); } catch (IOException e) {} }