Advanced Network Programming Lab using Java. Angelos Stavrou



Similar documents
Introduction to Java. Module 12: Networking (Java Sockets) Prepared by Costantinos Costa for EPL 233. ΕΠΛ233 Αντικειμενοστρεφής Προγραμματισμός 1

Lesson: All About Sockets

Essentials of the Java(TM) Programming Language, Part 1

Creating a Simple, Multithreaded Chat System with Java

Essentials of the Java Programming Language

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Homework/Program #5 Solutions

TP1 : Correction. Rappels : Stream, Thread et Socket TCP

CS 335 Lecture 06 Java Programming GUI and Swing

Learning Outcomes. Networking. Sockets. TCP/IP Networks. Hostnames and DNS TCP/IP

Network/Socket Programming in Java. Rajkumar Buyya

Division of Informatics, University of Edinburgh

DHBW Karlsruhe, Vorlesung Programmieren, Remote Musterlösungen

// Correntista. //Conta Corrente. package Banco; public class Correntista { String nome, sobrenome; int cpf;

public class demo1swing extends JFrame implements ActionListener{

Threads in der Client/Server-Programmierung mit Java

Graphical User Interfaces

Dev Articles 05/25/07 11:07:33

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

!"# $ %!&' # &! ())*!$

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Java Network Programming. The java.net package contains the Socket class. This class speaks TCP (connection-oriented protocol).

Java Network. Slides prepared by : Farzana Rahman

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Building a Multi-Threaded Web Server

Programming with Java GUI components

Java Appletek II. Applet GUI

file://c:\dokumente und Einstellungen\Marco Favorito\Desktop\ScanCmds.html

CS108, Stanford Handout #33. Sockets

Question1-part2 What undesirable consequences might there be in having too long a DNS cache entry lifetime?

Socket Programming in Java

INPUT AND OUTPUT STREAMS

Assignment 4 Solutions

Using A Frame for Output

Network Communication

Swing. A Quick Tutorial on Programming Swing Applications

Cours de Java. Sciences-U Lyon. Java - Introduction Java - Fondamentaux Java Avancé.

Introduction to the Java Programming Language

NETWORK PROGRAMMING IN JAVA USING SOCKETS

Network Programming using sockets

Application Development with TCP/IP. Brian S. Mitchell Drexel University

How To Write A Program For The Web In Java (Java)

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

Building a Java chat server


Mail User Agent Project

How Scala Improved Our Java

An Overview of Java. overview-1

Fondamenti di Java. Introduzione alla costruzione di GUI (graphic user interface)

Files and input/output streams

Tutorial Reference Manual. Java WireFusion 4.1

String sentence = new String(receivePacket.getData()); InetAddress IPAddress = receivepacket.getaddress(); int port = receivepacket.

Extending Desktop Applications to the Web

An Android-based Instant Message Application

WRITING DATA TO A BINARY FILE

Data Communication & Networks G

Nexawebホワイトペーパー. Developing with Nexaweb ~ Nexaweb to Improve Development Productivity and Maintainability

Lösningsförslag till tentamen

JAVA - FILES AND I/O

import java.net.*; java.net.*; IP (Internet Protocol) UDP & TCP Ports & sockets Program-to-program communications over IP

The difference between TCP/IP, UDP/IP and Multicast sockets. How servers and clients communicate over sockets

What is an I/O Stream?

JAVA Program For Processing SMS Messages

Event-Driven Programming

CS506 Web Design and Development Solved Online Quiz No. 01

Transport layer protocols. Message destination: Socket +Port. Asynchronous vs. Synchronous. Operations of Request-Reply. Sockets

The Design and Implementation of Multimedia Software

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Summer Internship 2013

Capario B2B EDI Transaction Connection. Technical Specification for B2B Clients

13 File Output and Input

public static void main(string[] args) { System.out.println("hello, world"); } }

Database Access from a Programming Language: Database Access from a Programming Language

Database Access from a Programming Language:

Callbacks. Callbacks Copyright 2007 by Ken Slonneger 1

Socket-based Network Communication in J2SE and J2ME

Socket programming. Socket Programming. Languages and Platforms. Sockets. Rohan Murty Hitesh Ballani. Last Modified: 2/8/2004 8:30:45 AM

Skills and Topics for TeenCoder: Java Programming

The Java I/O System. Binary I/O streams (ascii, 8 bits) The decorator design pattern Character I/O streams (Unicode, 16 bits)

Lab 9. Spam, Spam, Spam. Handout 11 CSCI 134: Spring, To gain experience with Strings. Objective

Using NetBeans IDE for Desktop Development. Geertjan Wielenga

Socket Programming. Announcement. Lectures moved to

Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013

TP #4 b. ClientBourse.java Classe principale du client graphique et fonction main.

Remote Method Invocation

Consuming a Web Service(SOAP and RESTful) in Java. Cheat Sheet For Consuming Services in Java

11. Applets, normal window applications, packaging and sharing your work

Object-Oriented Programming in Java

Threads & Tasks: Executor Framework

CSE 1223: Introduction to Computer Programming in Java Chapter 7 File I/O

Syllabus for CS 134 Java Programming

Transcription:

Advanced Network Programming Lab using Java Angelos Stavrou

Table of Contents A simple Java Client...3 A simple Java Server...4 An advanced Java Client...5 An advanced Java Server...8 A Multi-threaded Java Server...12 2

A simple Java Client import java.io.*; import java.net.*; public class ISAClient { public static void main(string[] args) throws Exception { String message; String returnmessage; BufferedReader keyboard = new BufferedReader(new InputStreamReader(System.in)); //server has to be listening to this port Socket mysock = new Socket("localhost",19000); DataOutputStream out = new DataOutputStream( mysock.getoutputstream()); BufferedReader in = new BufferedReader(new InputStreamReader(mysock.getInputStream())); message = keyboard.readline(); out.writebytes(message + "\n"); returnmessage = in.readline(); System.out.println("Server Said: " + returnmessage); mysock.close(); 3

A simple Java Server import java.io.*; import java.net.*; public class ISAServer { public static void main(string args[]) throws Exception { String message; String messagereturn; ServerSocket serversock = new ServerSocket(19000); //can be any port while(true) { Socket connsock = serversock.accept(); InputStreamReader instr = new InputStreamReader(connsock.getInputStream()); DataOutputStream outstr = new DataOutputStream(connsock.getOutputStream()); BufferedReader in = new BufferedReader(instr); message = in.readline(); messagereturn = "You sent this to server: " +message.touppercase() + "\n"; outstr.writebytes(messagereturn); 4

An advanced Java Client (example from http://java.sun.com/developer/onlinetraining/programming/basicjava2/socket.html) import java.awt.color; import java.awt.borderlayout; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; class SocketClient extends JFrame implements ActionListener { JLabel text, clicked; JButton button; JPanel panel; JTextField textfield; Socket socket = null; PrintWriter out = null; BufferedReader in = null; SocketClient(){ //Begin Constructor text = new JLabel("Text to send over socket:"); textfield = new JTextField(20); button = new JButton("Click Me"); button.addactionlistener(this); panel = new JPanel(); panel.setlayout(new BorderLayout()); 5

panel.setbackground(color.white); getcontentpane().add(panel); panel.add("north", text); panel.add("center", textfield); panel.add("south", button); //End Constructor public void actionperformed(actionevent event){ Object source = event.getsource(); if(source == button){ //Send data over socket String text = textfield.gettext(); out.println(text); textfield.settext(new String("")); //Receive text from server String line = in.readline(); System.out.println("Text received :" + line); catch (IOException e){ System.out.println("Read failed"); System.exit(1); public void listensocket(){ //Create socket connection socket = new Socket("kq6py", 4444); out = new PrintWriter(socket.getOutputStream(), true); in = new BufferedReader(new InputStreamReader(socket.getInputStream())); catch (UnknownHostException e) { 6

System.out.println("Unknown host: kq6py.eng"); System.exit(1); catch (IOException e) { System.out.println("No I/O"); System.exit(1); public static void main(string[] args){ SocketClient frame = new SocketClient(); frame.settitle("client Program"); WindowListener l = new WindowAdapter() { public void windowclosing(windowevent e) { System.exit(0); ; frame.addwindowlistener(l); frame.pack(); frame.setvisible(true); frame.listensocket(); 7

An advanced Java Server (example from http://java.sun.com/developer/onlinetraining/programming/basicjava2/socket.html) import java.awt.color; import java.awt.borderlayout; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; class SocketServer extends JFrame implements ActionListener { JButton button; JLabel label = new JLabel("Text received over socket:"); JPanel panel; JTextArea textarea = new JTextArea(); ServerSocket server = null; Socket client = null; BufferedReader in = null; PrintWriter out = null; String line; SocketServer(){ //Begin Constructor button = new JButton("Click Me"); button.addactionlistener(this); panel = new JPanel(); panel.setlayout(new BorderLayout()); panel.setbackground(color.white); getcontentpane().add(panel); 8

panel.add("north", label); panel.add("center", textarea); panel.add("south", button); //End Constructor public void actionperformed(actionevent event) { Object source = event.getsource(); if(source == button){ textarea.settext(line); public void listensocket(){ server = new ServerSocket(4444); catch (IOException e) { System.out.println("Could not listen on port 4444"); client = server.accept(); catch (IOException e) { System.out.println("Accept failed: 4444"); in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(), true); 9

catch (IOException e) { System.out.println("Accept failed: 4444"); while(true){ line = in.readline(); //Send data back to client out.println(line); catch (IOException e) { System.out.println("Read failed"); protected void finalize(){ //Clean up in.close(); out.close(); server.close(); catch (IOException e) { System.out.println("Could not close."); public static void main(string[] args){ SocketServer frame = new SocketServer(); frame.settitle("server Program"); WindowListener l = new WindowAdapter() { 10

public void windowclosing(windowevent e) { System.exit(0); ; frame.addwindowlistener(l); frame.pack(); frame.setvisible(true); frame.listensocket(); 11

A Multi-threaded Java Server import java.awt.color; import java.awt.borderlayout; import java.awt.event.*; import javax.swing.*; import java.io.*; import java.net.*; class ClientWorker implements Runnable { private Socket client; private JTextArea textarea; ClientWorker(Socket client, JTextArea textarea) { this.client = client; this.textarea = textarea; public void run(){ String line; BufferedReader in = null; PrintWriter out = null; in = new BufferedReader(new InputStreamReader(client.getInputStream())); out = new PrintWriter(client.getOutputStream(), true); catch (IOException e) { System.out.println("in or out failed"); while(true){ 12

line = in.readline(); //Send data back to client out.println(line); textarea.append(line); catch (IOException e) { System.out.println("Read failed"); class SocketThrdServer extends JFrame{ JLabel label = new JLabel("Text received over socket:"); JPanel panel; JTextArea textarea = new JTextArea(); ServerSocket server = null; SocketThrdServer(){ //Begin Constructor panel = new JPanel(); panel.setlayout(new BorderLayout()); panel.setbackground(color.white); getcontentpane().add(panel); panel.add("north", label); panel.add("center", textarea); //End Constructor public void listensocket(){ server = new ServerSocket(4444); catch (IOException e) { 13

System.out.println("Could not listen on port 4444"); while(true){ ClientWorker w; w = new ClientWorker(server.accept(), textarea); Thread t = new Thread(w); t.start(); catch (IOException e) { System.out.println("Accept failed: 4444"); protected void finalize(){ //Objects created in run method are finalized when //program terminates and thread exits server.close(); catch (IOException e) { System.out.println("Could not close socket"); public static void main(string[] args){ SocketThrdServer frame = new SocketThrdServer(); frame.settitle("server Program"); WindowListener l = new WindowAdapter() { public void windowclosing(windowevent e) { System.exit(0); 14

; frame.addwindowlistener(l); frame.pack(); frame.setvisible(true); frame.listensocket(); 15