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



Similar documents
NETWORK PROGRAMMING IN JAVA USING SOCKETS

Network/Socket Programming in Java. Rajkumar Buyya

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

Java Network. Slides prepared by : Farzana Rahman

Socket Programming in Java

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

Network Communication

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

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

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

Network Programming using sockets

Creating a Simple, Multithreaded Chat System with Java

Java Programming: Sockets in Java

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

Data Communication & Networks G

Division of Informatics, University of Edinburgh

Corso di Reti di Calcolatori

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

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

Assignment 4 Solutions

Corso di Reti di Calcolatori. java.net.inetaddress

CS 1302 Ch 19, Binary I/O

SSC - Communication and Networking Java Socket Programming (II)

INPUT AND OUTPUT STREAMS

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

Principles, Models, and Applications for Distributed Systems M

Socket-based Network Communication in J2SE and J2ME

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

Lesson: All About Sockets

File I/O - Chapter 10. Many Stream Classes. Text Files vs Binary Files

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

Building a Multi-Threaded Web Server

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

Socket Programming. Announcement. Lectures moved to

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

JAVA Program For Processing SMS Messages

Simple Java I/O. Streams

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

Socket programming. Complement for the programming assignment INFO-0010

Abstract Stream Socket Service

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

Network-based Applications. Pavani Diwanji David Brown JavaSoft

Advanced Network Programming Lab using Java. Angelos Stavrou

WRITING DATA TO A BINARY FILE

Slides for Chapter 4: Interprocess Communication

An Android-based Instant Message Application

AVRO - SERIALIZATION

D06 PROGRAMMING with JAVA

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

Tutorial on Socket Programming

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

A Tutorial on Socket Programming in Java

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

Preface. Intended Audience

Goal: learn how to build client/server application that communicate using sockets. An interface between application and network

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

Today s Outline. Computer Communications. Java Communications uses Streams. Wrapping Streams. Stream Conventions 2/13/2016 CSE 132

Threads in der Client/Server-Programmierung mit Java

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

What is an I/O Stream?

Mail User Agent Project

READING DATA FROM KEYBOARD USING DATAINPUTSTREAM, BUFFEREDREADER AND SCANNER

Communicating with a Barco projector over network. Technical note

Chapter 20 Streams and Binary Input/Output. Big Java Early Objects by Cay Horstmann Copyright 2014 by John Wiley & Sons. All rights reserved.

Session NM059. TCP/IP Programming on VMS. Geoff Bryant Process Software

Building a Java chat server

Principles of Software Construction: Objects, Design, and Concurrency. Design Case Study: Stream I/O Some answers. Charlie Garrod Jonathan Aldrich

Socket Programming in C/C++

NETWORKING FEATURES OF THE JAVA PROGRAMMING LANGUAGE

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

Computer Networks. Instructor: Niklas Carlsson

CHAPTER 6. Transmission Control Protocol. 6.1 Overview

Chapter 10. A stream is an object that enables the flow of data between a program and some I/O device or file. File I/O

JAVA - FILES AND I/O

TITLE NETWORK PROGRAMMING (SECURED CLIENT-SERVER CHAT APPLICATION) A PROJECT REPORT PRESENTED ACHILE UGBEDE JOHN CE/2007/165

Network Programming TDC 561

UNIX Sockets. COS 461 Precept 1

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

Chapter 2: Application layer

Computer Networks/DV2 Lab

SMTP-32 Library. Simple Mail Transfer Protocol Dynamic Link Library for Microsoft Windows. Version 5.2

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

Programming in Java

FILE I/O IN JAVA. Prof. Chris Jermaine Prof. Scott Rixner

Introduction to Socket programming using C

Transparent Redirection of Network Sockets 1

Crash Course in Java

Cross-platform TCP/IP Socket Programming in REXX

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

Socket Programming. Srinidhi Varadarajan

FTP client Selection and Programming

Lab 4: Socket Programming: netcat part

Introduction to Computer Networks

Manual. Programmer's Guide for Java API

The exam has 110 possible points, 10 of which are extra credit. There is a Word Bank on Page 8. Pages 7-8 can be removed from the exam.

CS506 Web Design and Development Solved Online Quiz No. 01

Transparent Redirection of Network Sockets 1

Java Fundamental Classes Reference

All rights reserved. Copyright in this document is owned by Sun Microsystems, Inc.

Transcription:

Sockets Programação de Sockets em Java Server ports lients user space TP/UDP Socket API TP/UDP kernel space IP IP Ethernet Adapter Ethernet Adapter hardware SISTEMAS INFORMÁTIOS I, ENG. BIOMÉDIA SLIDES_10 Socket Abstractions amada de Transporte File server Mail server WWW server UDP: User Datagram Protocol - no acknowledgements - no retransmissions - out of order, duplicates possible - connectionless TP: Transmission ontrol Protocol - reliable (in order, all arrive, no duplicates) - flow control - connection 1

Package java.net The java.net package provides networking support in java. InetAddress The java.net.inetaddress class represents an IP address. lasses DatagramPacket DatagramSocket InetAddress ServerSocket Socket Exceptions BindException onnectexception MalformedURLException NoRouteToHostException ProtocolException SocketException UnknownHostException UnknownServiceException - public byte[] getaddress(); - public static InetAddress[] getallbyname(string host); - public static InetAddress getbyname(string host); - public String gethostname(); - public static InetAddress getlocalhost(); Exemplo: InetAddress import java.io.* ; import java.net.* ; public class InetAddressTest { public static void main( String args[] ) { try { InetAddress myself = InetAddress.getLocalHost(); InetAddress machine = InetAddress.getByName("www.dei.uc.pt"); System.out.println("My name : " + myself.gethostname()); System.out.println("My IP : " + myself.gethostaddress()); System.out.println("UnivSite name : " + machine.gethostname()); System.out.println("UnivSite IP : " + machine.gethostaddress()); catch (UnknownHostException e) { System.out.println ("ould not find address "); catch (IOException e) { System.out.println (e); Ports Port numbers can be: Well-known (port 0-1023) Dynamic or private (port 1024-65535) Servers/daemons usually use well-known ports Any client can identify the server/service HTTP = 80, FTP = 21, Telnet = 23,... lients usually use dynamic ports Assigned by the kernel at run time A full address for a socket is then: IP address + port number ex: student.dei.uc.pt: 8080 130.194.49.81: 9090 NTP daemon TP/UDP IP Web server port 123 port 80 Ethernet Adapter 2

Sockets Stream Stream Sockets (TP) class Socket onnects to a ServerSocket. class ServerSocket Accepts requests for socket connections. reates a new Socket for each connection. TP service: reliable transfer of bytes from one process to another riação de Sockets Server and Ports Each Socket object is associated with exactly one remote host. To connect to a different host, you must create a new Socket object. You specify the remote host and the port to connect. The host may be specified as a string like eden.dei.uc.pt" or an InetAddress object. The port should be an int between 1 and 65535. Socket s = new Socket( www.dei.uc.pt",80); On Unix systems (but not Windows) your program must be running as root to bind to a port between 1 and 1023. 0 is a special port number. It tells the system to pick on of the available ports. Many well known ports echo 7 time 13 ftp 21 telnet 23 finger 79 smpt 25 http 80 3

lients and Ports lient/server socket interaction: TP The client is assigned a port number on the local machine as part of establishing the connection. How to know the number of the local port: getlocalport() A client can connect to a particular port by using programs such as telnet, as follows: telnet www.dei.uc.pt 80 hostid create socket, port=x, for incoming request: welcomesocket = ServerSocket() wait for incoming connection request connectionsocket = welcomesocket.accept() read request from connectionsocket write reply to connectionsocket close connectionsocket create socket, connect to hostid, port=x clientsocket = Socket() send request using clientsocket read reply from clientsocket close clientsocket Socket Socket(InetAddress address, int port) reates a stream socket and connects it to the specified port number at the specified IP address. InputStream getinputstream() Returns an input stream for this socket. OutputStream getoutputstream() Returns an output stream for this socket. void close() closes this socket (cuts the connection) ServerSocket A server socket that can wait for connections from other machines public ServerSocket(int port) throws IOException reates a ServerSocket that will receive connection requests on the specified port. public Socket accept() throws IOException Waits for an incoming connection request, creates the connection, and returns the Socket created on this end. public void close() throws IOException closes the socket connection. 4

ServerSockets A ServerSocket binds to a particular local port. Then it calls accept() to listen for incoming connections; accept() blocks until a connection is detected. When accept() unblocks this means that a client has connected. It returns a Socket object which is used to communicate with the remote client. There are no getinputstream() or getoutputstream() methods for ServerSocket. Server ServerSocket(1234) Output/write stream lient Input/read stream Socket( 128.250.25.158, 1234) Exemplo: ServerSocket 1. class ServerExample { 2. public static void main(string[] args) { 3. try { 4. ServerSocket ssock = new ServerSocket(3333); 5. Socket sock = ssock.accept(); 6. BufferedReader br = new BufferedReader( 7. new InputStreamReader(sock.getInputStream())); 8. System.out.println(br.readLine()); 9. sock.close(); 10. catch(exception e) {... 11. Exemplo: client Socket class lientexample { public static void main(string[] args) { try { Socket sock = new Socket( server.dei.uc.pt, 3333); PrintWriter out = new PrintWriter( sock.getoutputstream(), true); out.println( Hello ); sock.close(); catch(exception e) {... 5

BufferedReader methods void close() lose the stream. int read() Read a single character. int read(char[] cbuf, int off, int len) Read characters into a portion of an array. String readline() Read a line of text. DataInputStream methods int read(byte[] b) reads some number of bytes into the buffer array b. int read(byte[] b, int off, int len) reads up to len bytes into an array of bytes. char readhar() reads a char. double readdouble() reads a double value. int readint() reads a int value. void readfully(byte[] b) reads some bytes and stores them into the buffer array. String readline() Deprecated. This method does not properly convert bytes to characters. The preferred way to read lines of text is via the BufferedReader.readLine() method. Programs that use the DataInputStream class to read lines can be converted to use the BufferedReader class by replacing code of the form: DataInputStream d = new DataInputStream(in); with: BufferedReader d = new BufferedReader(new InputStreamReader(in)); String readutf() reads a string (encoded in UTF-8 format). DataOutputStream methods PrintWriter methods void flush() flushes this data output stream. void write(int b) writes the specified byte. void writedouble(double v) writes a double. void writeint(int v) writes an int. void writeutf(string str) Writes a string. void close() lose the stream. void flush() Flush the stream. void print(char c) Print a character. void print(char[] s) Print an array of chars. void print(double d) Print a double. void print(int i) Print an integer. void print(object obj) Print an object. void print(string s) Print a string. void write(char[] buf) Write an array of chars. 6

Exceptions Exceptions exceptions: Almost all methods in networking classes throw IOExceptions that must be caught because of potential network problems. try { Socket client = new Socket(host, port); handleonnection(client); catch(unknownhostexception uhe) { System.out.println("Unknown host: " + host); uhe.printstacktrace(); catch(ioexception ioe) { System.out.println("IOException: " + ioe); ioe.printstacktrace(); liente Outro Exemplo: Sockets TP // 1. reate a Socket Object: client = new Socket( server, port_id ); // 2. reate I/O streams for communicating with the server. is = new DataInputStream(client.getInputStream() ); os = new DataOutputStream( client.getoutputstream() ); // 3. Perform I/O or communication with the server: // Receive data from the server: String line = is.readline(); // Send data to the server: os.writebytes("hello\n"); // 4. lose the socket when done: client.close(); 7

Server // 1- Open the Server Socket: ServerSocket server; DataOutputStream os; DataInputStream is; server = new ServerSocket( PORT ); // 2- Wait for the lient Request: Socket client = server.accept(); // 3- reate I/O streams for communicating to the client is = new DataInputStream( client.getinputstream() ); os = new DataOutputStream( client.getoutputstream() ); // 4- Perform communication with client // Receive from client: String line = is.readline(); // Send to client: os.writebytes("hello\n"); // 5- lose sockets: client.close(); For multithreaded server: while(true) { i. wait for client requests (step 2 above) ii. create a thread with client socket as parameter (the thread creates streams (as in step (3) and does communication as stated in (4). Remove thread once service is provided. Simple Server import java.io.*; public class SimpleServer{ public static void main(string args[]) throws IOException { // Register service on port 1234 ServerSocket s = new ServerSocket(1234); while(true){ Socket s1=s.accept(); // Wait and accept a connection // Get a stream associated with the socket OutputStream s1out = s1.getoutputstream(); DataOutputStream dos = new DataOutputStream (s1out); // Send a string! dos.writeutf("ola Boa Noite"); System.out.println("Respondeu ao cliente"); // lose the connection, but not the server socket dos.close(); s1out.close(); s1.close(); Try this example... Simple lient // Simplelient.java: a simple client program import java.net.*; import java.io.*; public class Simplelient { public static void main(string args[]) throws IOException { // Open your connection to a server, at port 1234 Socket s1 = new Socket( localhost",1234); // Get an input file handle from the socket and read the input InputStream s1in = s1.getinputstream(); DataInputStream dis = new DataInputStream(s1In); String st = new String (dis.readutf()); System.out.println(st); // When done, just close the connection and exit dis.close(); s1in.close(); s1.close(); Try this example... Run SimpleServer, Simplelient Run Server on localhost: java SimpleServer Run lient: java Simplelient Ola, Boa Noite If you run client when server is not up: sockets [1:147] java Simplelient Exception in thread "main" java.net.onnectexception: onnection refused at java.net.plainsocketimpl.socketonnect(native Method) at java.net.plainsocketimpl.doonnect(plainsocketimpl.java:320) at java.net.plainsocketimpl.connecttoaddress(plainsocketimpl.java:133) at java.net.plainsocketimpl.connect(plainsocketimpl.java:120) at java.net.socket.<init>(socket.java:273) at java.net.socket.<init>(socket.java:100) at Simplelient.main(Simplelient.java:6) 8

Binding When a ServerSocket object is created, it attempts to bind to the port on the local host given by the port argument. If another server socket is already listening to the port, there will be ajava.net.bindexception. No more than one process or thread can listen to a particular port at a time. For example, if there's already an HTTP server running on port 80, you won't be able to bind to port 80. Multiple lients Multiple clients can connect to the same port on the server at the same time. The server creates a separate socket for each client. Multithreaded Server Multi-Threaded Servers If a server needs to handle many connections at once, server programs should be multi-threaded. lient 1 Process Server Process TP/IP Server Threads lient 2 Process 9

Multi-threaded Server Multi-threaded Server (I) One ServerSocket can accept multiple clients simultaneously Use multithreading to handle them One thread waits for accept() Open a new thread for each connection. Rather than handling the connection directly the socket should be passed to a Thread object that handles the connection. ServerSocket server = new ServerSocket(PORT); // Server main loop while (true) { try { Socket clientsocket = server.accept(); lientthread thelient = new lientthread(clientsocket); thelient.start(); catch (Exception e) { // Error accepting one of the clients e.printstacktrace(); Multi-threaded Server (II) class lientthread extends Thread { private Socket clientsocket; public lientthread(socket clientsocket) { this.clientsocket = clientsocket; Threading a Server Threads handles the communication between one client and the server, by spawning a new thread every time a new client connects. This is often accomplished in /++ on a Unix OS by using fork. Nowadays the use of Pthreads is also common. In Java it is simpler thanks to the use of Java Threads. public void run() { // Handle the client request here! 10

TDayTimeServer.java onnection.java import java.net.*; import java.io.*; import java.util.*; public class TDayTimeServer { public static void main(string argv[]) { try { ServerSocket listen = new ServerSocket(0); System.out.println("Listening on:"+listen.getlocalport()); for(;;) { Socket client = listen.accept(); System.out.println(clnt.toString()); onnection c = new onnection(client); catch(exception e) { System.out.println("Server terminated"); import java.net.*; import java.io.*; import java.util.*; class onnection extends Thread { protected Socket clnt; public onnection(socket sock) { clnt = sock; this.start(); public void run() { Date today = new Date(); try { PrintWriter out = new PrintWriter(clnt.getOutputStream(), true); out.println(today); client.close(); catch (IOException e) { Exemplos_Sockets.zip UDP Datagrams -TPlient.java -TPServer1.java -TPServer2.java (multithreaded server) 11

UDP - Java lasses DatagramSocket DatagramPacket represents a datagram packet DatagramSocket represents a socket for sending and receiving datagram packets MulticastSocket for sending and receiving IP multicast packets // onstructors DatagramSocket() onstructs a datagram socket and binds it to any available port on the local host machine. DatagramSocket(int port) onstructs a datagram socket and binds it to the specified port on the local host machine. DatagramSocket(int port, InetAddress iaddr) // Methods void close() InetAddress getlocaladdress() int getlocalport() int getsotimeout() void receive(datagrampacket p) void send(datagrampacket p) setsotimeout(int timeout) lient/server socket interaction: UDP DatagramPacket hostid create socket, port=x, for incoming request: S_Socket = DatagramSocket() read request from S_Socket write reply to S_Socket specifying client host address, port number create socket, _Socket = DatagramSocket() reate, address (hostid, port=x, send datagram request using _Socket read reply from _Socket close _Socket //onstructors public DatagramPacket(byte[] buf, int length) onstructs a DatagramPacket for receiving. public DatagramPacket(byte[] buf, int length, InetAddress address, int port) onstructs a datagram for sending to the specified port number on the specified host. // Methods public synchronized InetAddress getaddress(); public synchronized int getport(); public synchornized byte[] getdata(); int getlength(); void setaddress(inetaddress iaddr); void setport(int iport); void setdata(byte ibuf[]); void setlength(int ilength); 12

DatagramPacket Datagram packet data is stored as a byte array: byte[]. To send a String message via a datagram we need to convert it to byte[]. The String class provides this via the getbytes() method. String msg = Olá ; byte[] buf = msg.getbytes(); Sending UDP Datagrams To send data to a particular server onvert the data into byte array. Pass this byte array, its length, the InetAddress and the destination port to the DatagramPacket() constructor. Next create a DatagramSocket and send the packet by using the send() method. Sending a DatagramPacket DatagramSocket try { InetAddress addr = InetAddress.getByName( eden.dei.uc.pt"); int port = 9000; String msg = Olá Boa Noite"; byte[] msgbytes = msg.getbytes(); DatagramPacket packet = new DatagramPacket(msgBytes, msgbytes.length, addr, port); DatagramSocket sender = new DatagramSocket(); sender.send(packet); catch (Exception e) { System.err.println(e); public void send(datagrampacket p) throws IOException Sends a datagram packet from this socket. The DatagramPacket includes information indicating the data to be sent, its length, the IP address of the remote host, and the port number on the remote host. 13

DatagramSocket public void receive(datagrampacket p) throws IOException Receives a datagram packet from this socket. When this method returns, the DatagramPacket's buffer is filled with the data received. The datagram packet also contains the sender's IP address, and the port number on the sender's machine. It blocks until a datagram packet is received. If the message is longer than byte[] the message will be truncated UDP + TP Ports There are separated ports for UDP and TP. Each computer has 65,536 UDP ports as well as its 65,536 TP ports. A server socket can be bound to TP port 20 at the same time as a datagram socket is bound to UDP port 20. DatagramSocket (client) DatagramSocket socket = new DatagramSocket(); // send request InetAddress address = InetAddress.getByName( eden.dei.uc.pt ); String s = get_current_time_date ; byte [] b = s.getbytes(); DatagramPacket packet = new DatagramPacket(b, b.length, address, 4445); socket.send(packet); // get response byte[] buf = new byte[256]; packet = new DatagramPacket(buf, buf.length); socket.receive(packet); // display response String received = new String(packet.getData()); System.out.println( the time: + received); socket.close(); DatagramSocket (server) DatagramSocket socket = new DatagramSocket(); // receives a packet request byte[] buf = new byte[256]; DatagramPacket packetrequest = new DatagramPacket(buf, buf.length); socket.receive(packetrequest); // Display the request byte[] data = packetrequest.getdata(); String s = new String(data, 0, data.getlength()); System.out.println("Port " + packet1.getport() + " on " + packet1.getaddress() + " sent this message: + s); if (s.equals( get_current_time_date )) { String thedate = (new Date()).toString(); byte[] bufsend = thedate.getbytes(); InetAddress address = packetrequest.getaddress(); int port = packetrequest.getport(); DatagramPacket responsepacket = new DatagramPacket(bufSend,bufSend.length,address,port); socket.send(responsepacket); 14

Datagrams Received... Use getport() and getaddress() to tell where the packet come from, getdata() to retrieve the data, and getlength() to see how many bytes were in the data. If the received packet was too long for the buffer, it's truncated to the length of the buffer. Length is reset when packet is received. Exemplos_Sockets.zip -UDPlient.java -UDPServer.java Uso de Recursos: TP vs UDP N clientes simultâneos N sockets no Servidor TP SERVER ServerSocket Leitura de Mensagens Grandes em Sockets Stream Socket Socket Socket Socket Socket Socket UDP SERVER Socket int size,tam=0; while(tam < N){ size=in.readbytes(...); tam = tam + size; N clientes simultâneos 1 socket no Servidor 15

Objectos Programamos objectos complexos. Object Serialization Queremos guardar o estado dos objectos em disco.. Queremos enviar objectos para outros processos através de um socket... Object Serialization Object Serialization Suppose that you have an object and want to send it across a socket ( ) Pessoa p = new Pessoa( Bush, 50); // enviar o objecto p através de um socket ( ) public class Pessoa{ private String name; private int age; public Pessoa(String name, int age) { this.name = name; this.age = age; public String tostring() { return "[" + name + "/" + age + "]"; Object Serialization It is possible to send complete objects through a socket stream ObjectInputStream.readObject() ObjectOutputStream.writeObject() When reading an object from a ObjectInputStream, it is necessary to cast it to the appropriate type Pessoa p = (Pessoa) in.readobject(); For being able to send object through a stream, they must be serializable (i.e. they must implement java.io.serializable) Although many classes are serializable, some are not Ex: a Thread is not serializable 16

Guardar Objectos em Disco 1. Mark your class serializable public class MylassA implements Serializable {... // in some other code elsewhere... MylassA tmp=new MylassA(arg); FileOutputStream fos=new FileOutputStream( some.obj ); ObjectOutputStream out=new ObjectOutputStream(fos); out.writeobject(tmp); out.flush(); out.close(); public class Pessoa implements java.io.serializable { private String name; private int age; public Pessoa(String name, int age) { this.name = name; this.age = age; public String tostring() { return "[" + name + "/" + age + "]"; 2. Use the ObjectStreams Reading ObjectInputStream in = new ObjectInputStream(clientSocket.getInputStream()); Pessoa x = (Pessoa) in.readobject(); System.out.println(x); Writing ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream()); Pessoa p = new Pessoa( Busha, 50); out.writeobject(p); Examplo Serialização Objectos class Data implements Serializable { private int i; private int tabela[]; public Data(int x){ i = x; tabela = new int[10]; for(int j=0;j<10;j++) tabela[j]=x; public String tostring() { return Integer.toString(i); public void print_conteudo() { for(int j=0;j<10;j++) System.out.print(tabela[j]+" " ); System.out.println(); 17

lient: TPlient_O public class TPlient_O { public static void main (String args[]) { String texto; Socket s = null; int serversocket = 6000; try{ // 1o passo s = new Socket(host, serversocket); // // 2o passo DataInputStream in = new DataInputStream( s.getinputstream()); DataOutputStream out = new DataOutputStream( s.getoutputstream()); // riar ObjecOutputStream e ObjectInputStream ObjectOutputStream obj_o = new ObjectOutputStream(out); ObjectInputStream obj_i = new ObjectInputStream(in); int contador=0; // 3o passo while(contador < 5){ contador++; Data d = new Data(contador); obj_o.writeobject(d); obj_o.flush(); d.print_conteudo(); System.out.println("ENVIEI OBJETO"); String data = in.readutf(); System.out.println("Received: "+ data); Server: TPServer1_O public class TPServer1_O{ public static void main(string args[]) throws IOException,lassNotFoundException{ int serverport = 6000; // listensocket = new ServerSocket(serverPort); while(true){ System.out.println("A esperade ligacaono socket "+serverport); try{ clientsocket = listensocket.accept(); in = new DataInputStream(clientSocket.getInputStream()); out = new DataOutputStream(clientSocket.getOutputStream()); // riar ObjectinputStream e ObjectOutputStream ObjectOutputStream obj_o = new ObjectOutputStream(out); ObjectInputStream obj_i = new ObjectInputStream(in); Data d; while(true){ d = (Data)obj_i.readObject(); System.out.println("Recebeu: "+d); d.print_conteudo(); out.writeutf("objeto OK"); out.flush(); // while //... catches. //... catches... Overwriting writeobject/readobject Exemplos_Sockets.zip -TPlient_O.java -TPServer1_O.java public class Demolass implements Serializable { private int _dat=3; private static int _sdat=2; private void writeobject(objectoutputstream o) throws IOException { o.writeint(_dat); o.writeint(_sdat); private void readobject(objectinputstream i) throws IOException, lassnotfoundexception { _dat=i.readint(); _sdat=i.readint(); 18

Objecto com partes não-serializáveis What happens if class Foo has a field of type Bar, but Bar isn t serializable? Foo tmp=new Foo(); ObjectOutputStream out=new ObjectOutputStream; out.writeobject(tmp); You get a NotSerializableException Answer: use read/writeobject to explicitly serialize parts that can t be handled otherwise 19