Socket Programming in Java



Similar documents
NETWORK PROGRAMMING IN JAVA USING SOCKETS

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

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

Assignment 4 Solutions

Java Programming: Sockets in Java

An Introduction to Network Programming with Java

Lesson: All About Sockets

Socket-based Network Communication in J2SE and J2ME

Java Network. Slides prepared by : Farzana Rahman

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

Socket Programming. A er learning the contents of this chapter, the reader will be able to:

Network-based Applications. Pavani Diwanji David Brown JavaSoft

CISC 4700 L01 Network & Client- Server Programming Spring Harold, Chapter 8: Sockets for Clients

Division of Informatics, University of Edinburgh

SSC - Communication and Networking Java Socket Programming (II)

Network Communication

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

Network Programming using sockets

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

Preface. Intended Audience

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

Package java.net. Interfaces. Classes. Exceptions. Package java.net Page 1 of 1. All Packages

Creating a Simple, Multithreaded Chat System with Java

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

Socket Programming. Announcement. Lectures moved to

Network/Socket Programming in Java. Rajkumar Buyya

! "# $%&'( ) * ).) "%&' 1* ( %&' ! "%&'2 (! ""$ 1! ""3($

Data Communication & Networks G

Abstract Stream Socket Service

Building a Multi-Threaded Web Server

Domain Name System (DNS) Omer F. Rana. Networks and Data Communications 1

Abhijit A. Sawant, Dr. B. B. Meshram Department of Computer Technology, Veermata Jijabai Technological Institute

NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE

Java Fundamental Classes Reference

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

Corso di Reti di Calcolatori. java.net.inetaddress

CHAPTER 6. Transmission Control Protocol. 6.1 Overview

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

Mail User Agent Project

DNS: Domain Names. DNS: Domain Name System. DNS: Root name servers. DNS name servers

When the transport layer tries to establish a connection with the server, it is blocked by the firewall. When this happens, the RMI transport layer

Communicating with a Barco projector over network. Technical note

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

Sockets. Programação de Sockets em Java. Socket Abstractions. Camada de Transporte

Advanced Network Programming Lab using Java. Angelos Stavrou

Rappels programma,on réseau Java- suite. C. Delporte M2- Internet Rappel Java 1

INPUT AND OUTPUT STREAMS

Transparent Redirection of Network Sockets 1

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

Limi Kalita / (IJCSIT) International Journal of Computer Science and Information Technologies, Vol. 5 (3), 2014, Socket Programming

8. Java Network Programming

AVRO - SERIALIZATION

Socket programming. Complement for the programming assignment INFO-0010

An Overview of Java. overview-1

ExempleRMI.java. // Fichier de defintion des droits et proprietes // System.setProperty("java.security.policy","../server.java.

Files and input/output streams

Slides for Chapter 4: Interprocess Communication

13 File Output and Input

WRITING DATA TO A BINARY FILE

Chapter 02 Networking in Java

Contents. 9-1 Copyright (c) N. Afshartous

An Android-based Instant Message Application

Transparent Redirection of Network Sockets 1

Building a Java chat server

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

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

JAVA Program For Processing SMS Messages

Intranet, Extranet, Firewall

Agenda. Network Programming and Java Sockets. Introduction. Internet Applications Serving Local and Remote Users

Serializing Data with Protocol Buffers. Vinicius Vielmo Cogo Smalltalks, DI, FC/UL. February 12, 2014.

What is an I/O Stream?

Introduction to Socket Programming Part I : TCP Clients, Servers; Host information

Application Note 704 Asynchronous Serial-to-Ethernet Device Servers

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

Database Access from a Programming Language:

Mobila applikationer och trådlösa nät

CS506 Web Design and Development Solved Online Quiz No. 01

Remote Method Invocation

Preet raj Core Java and Databases CS4PR. Time Allotted: 3 Hours. Final Exam: Total Possible Points 75

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

JAVA - FILES AND I/O

Lecture 2-ter. 2. A communication example Managing a HTTP v1.0 connection. G.Bianchi, G.Neglia, V.Mancuso

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

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

Stream Classes and File I/O

Chapter 11. User Datagram Protocol (UDP)

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

Event-Driven Programming

Report of the case study in Sistemi Distribuiti A simple Java RMI application

Lecture J - Exceptions

A Tutorial on Socket Programming in Java

Logging in Java Applications

Scanner. It takes input and splits it into a sequence of tokens. A token is a group of characters which form some unit.

Evaluation. Copy. Evaluation Copy. Chapter 7: Using JDBC with Spring. 1) A Simpler Approach ) The JdbcTemplate. Class...

Transcription:

Socket Programming in Java

Learning Objectives The InetAddress Class Using sockets TCP sockets Datagram Sockets

Classes in java.net The core package java.net contains a number of classes that allow programmers to carry out network programming ContentHandler DatagramPacket DatagramSocket DatagramSocketImplHttpURLConnection InetAddress MulticastSocket ServerSocket Socket SocketImpl URL URLConnection URLEncoder URLStreamHandler

Exceptions in Java BindException ConnectException MalformedURLException NoRouteToHostException ProtocolException SocketException UnknownHostException UnknownServiceException

The InetAddress Class Handles Internet addresses both as host names and as IP addresses Static Method getbyname returns the IP address of a specified host name as an InetAddress object Methods for address/name conversion: public static InetAddress getbyname(string host) throws UnknownHostException public static InetAddress[] getallbyname(string host) throws UnknownHostException public static InetAddress getlocalhost() throws UnknownHostException public boolean ismulticastaddress() public String gethostname() public byte[] getaddress() public String gethostaddress() public int hashcode() public boolean equals(object obj) public String tostring()

import java.net.*; import java.io.*; public class IPFinder { public static void main(string[] args) throws IOException { String host; BufferedReader input = new BufferedReader( new InputStreamReader(System.in)); } System.out.print("\n\nEnter host name: "); host = input.readline(); try { InetAddress address = InetAddress.getByName(host); System.out.println("IP address: " + address.tostring()); } catch (UnknownHostException e) { System.out.println("Could not find " + host); } }

Retrieving the current machine s address import java.net.*; public class MyLocalIPAddress { public static void main(string[] args) { try { InetAddress address = InetAddress.getLocalHost(); System.out.println (address); } catch (UnknownHostException e) { System.out.println("Could not find local address!"); } } }

The Java.net.Socket Class Connection is accomplished through the constructors. Each Socket object is associated with exactly one remote host. To connect to a different host, you must create a new Socket object. public Socket(String host, int port) throws UnknownHostException, IOException public Socket(InetAddress address, int port) throws IOException public Socket(String host, int port, InetAddress localaddress, int localport) throws IOException public Socket(InetAddress address, int port, InetAddress localaddress, int localport) throws IOException Sending and receiving data is accomplished with output and input streams. There are methods to get an input stream for a socket and an output stream for the socket. public InputStream getinputstream() throws IOException public OutputStream getoutputstream() throws IOException There's a method to close a socket: public void close() throws IOException

The Java.net.SocketSocket Class The java.net.serversocket class represents a server socket. It is constructed on a particular port. Then it calls accept() to listen for incoming connections. accept() blocks until a connection is detected. Then accept() returns a java.net.socket object that is used to perform the actual communication with the client. public ServerSocket(int port) throws IOException public ServerSocket(int port, int backlog) throws IOException public ServerSocket(int port, int backlog, InetAddress bindaddr) throws IOException public Socket accept() throws IOException public void close() throws IOException

SERVER: TCP Sockets 1. Create a ServerSocket object ServerSocket servsocket = new ServerSocket(1234); 2. Put the server into a waiting state Socket link = servsocket.accept(); 3. Set up input and output streams 4. Send and receive data out.println(awaiting data ); String input = in.readline(); 5. Close the connection link.close()

Set up input and output streams Once a socket has connected you send data to the server via an output stream. You receive data from the server via an input stream. Methods getinputstream and getoutputstream of class Socket: BufferedReader in = new BufferedReader( new InputStreamReader(link.getInputStream())); PrintWriter out = new PrintWriter(link.getOutputStream(),true);

CLIENT: TCP Sockets 1. Establish a connection to the server Socket link = new Socket(inetAddress.getLocalHost(),1234); 2. Set up input and output streams 3. Send and receive data 4. Close the connection

The UDP classes 2 classes: java.net.datagramsocket class is a connection to a port that does the sending and receiving. Unlike TCP sockets, there is no distinction between a UDP socket and a UDP server socket. Also unlike TCP sockets, a DatagramSocket can send to multiple, different addresses.the address to which data goes is stored in the packet, not in the socket. public DatagramSocket() throws SocketException public DatagramSocket(int port) throws SocketException public DatagramSocket(int port, InetAddress laddr) throws SocketException java.net.datagrampacket class is a wrapper for an array of bytes from which data will be sent or into which data will be received. It also contains the address and port to which the packet will be sent. public DatagramPacket(byte[] data, int length) public DatagramPacket(byte[] data, int length, InetAddress host, int port)

Datagram Sockets SERVER: 1. Create a DatagramSocket object DatagramSocket dgramsocket = new DatagramSocket(1234); 2. Create a buffer for incoming datagrams byte[] buffer = new byte[256]; 3. Create a DatagramPacket object for the incoming datagram DatagramPacket inpacket = new DatagramPacket(buffer, buffer.length); 4. Accept an incoming datagram dgramsocket.receive(inpacket)

Datagram Sockets SERVER: 5. Accept the sender s address and port from the packet InetAddress clientaddress = inpacket.getaddress(); int clientport = inpacket.getport(); 6. Retrieve the data from the buffer string message = new String(inPacket.getData(), 0, inpacket.getlength()); 7. Create the response datagram DatagramPacket outpacket = new DatagramPacket( response.getbytes(), response.length(), clientaddress, clientport); 8. Send the response datagram dgramsocket.send(outpacket) 9. Close the DatagramSocket: dgram.close();

CLIENT: Datagram Sockets 1. Create a DatagramSocket object DatagramSocket dgramsocket = new DatagramSocket; 2. Create the outgoing datagram DatagramPacket outpacket = new DatagramPacket( message.getbytes(), message.length(), host, port); 3. Send the datagram message dgramsocket.send(outpacket) 4. Create a buffer for incoming datagrams byte[] buffer = new byte[256];

Datagram Sockets CLIENT: 5. Create a DatagramPacket object for the incoming datagram DatagramPacket inpacket = new DatagramPacket(buffer, buffer.length); 6. Accept an incoming datagram dgramsocket.receive(inpacket) 7. Retrieve the data from the buffer string response = new String(inPacket.getData(), 0, inpacket.getlength()); 8. Close the DatagramSocket: dgram.close();

References Jan Graba, An Introduction to Network Programming with Java, Addison-Wesley. Elliotte Rusty Harold, Java Network Programming, O Reilly&Associates.