Vous êtes sur la page 1sur 2

//Classe cliente

package cliente;
import java.io.Serializable;
public class cliente implements Serializable{
private static final long serialVersionUID = 100L;
private String nome = "";
private String endereco = "";
private String telefone = "";
public cliente() {}
cliente(String nome, String endereco, String telefone){
this.nome = nome;
this.endereco = endereco;
this.telefone = telefone;
}
}

----------------------------------------------------------
package serversocket;
import java.io.*;
import java.net.*;
import cliente.*;
public class Main {
private static Object clienteSocket;
private static DataOutputStream out;
private static DataInputStream in;
private static ObjectOutputStream oos;
public static void main(String[] args) {
Socket clientSocket = null;
cliente c = new cliente("Anselmo","Rua das pedras","9999-9999");
try{
int serverPort = 8000;
ServerSocket listenSocket = new ServerSocket(serverPort);
while(true){
// esta linha é bloqueante ou seja fica aqui enquanto
// um cliente não aceita
clientSocket= listenSocket.accept();
in = new DataInputStream(clientSocket.getInputStream());
out =new DataOutputStream(clientSocket.getOutputStream());
oos = new ObjectOutputStream(clientSocket.getOutputStream());
int a = in.readInt();
int b = in.readInt();
Integer soma = a+b;
out.writeUTF(soma.toString());
oos.writeObject(c);
}
} catch(EOFException e){
System.out.println("EOF:"+e.getMessage());
} catch(IOException e) {
System.out.println("IO:"+e.getMessage());
} finally {
try {
if (clienteSocket!= null)
clientSocket.close();
} catch (IOException e){/*close failed*/}
}// try
}// main
}// class
-----------------------------------------------------------------
package clientesocket;
import cliente.cliente;
import java.net.*;
import java.io.*;
import cliente.*;
public class Main {
public static void main (String args[]) throws IOException, ClassNotFoundExc
eption {
Socket s = null;
try{
int serverPort = 8000;
s = new Socket("127.0.0.1", serverPort);
DataInputStream in= new DataInputStream(s.getInputStream());
DataOutputStream out= new DataOutputStream(s.getOutputStream());
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream())
;
out.writeInt(10);
out.writeInt(20);
String data = in.readUTF();
cliente c = (cliente) ois.readObject();
System.out.println("A soma de 10 + 20 = "+data) ;
System.out.println("nome do cliente = "+c.nome);
}catch (UnknownHostException e){
System.out.println("Sock:"+e.getMessage());
}catch (EOFException e){
System.out.println("EOF:"+e.getMessage());
}catch (IOException e){
System.out.println("IO:"+e.getMessage());
} finally {
if(s!=null)
try {
s.close();
}
catch (IOException e){
System.out.println("close:"+e.getMessage());
}
}// try
} // main
} // class

Vous aimerez peut-être aussi