Anda di halaman 1dari 36

Ao de la Diversificacin Productiva y del Fortalecimiento de la Educacin

UNIVERSIDAD NACIONAL DE
UCAYALI
Facultad de Ingeniera de Sistemas y de Ingeniera Civil
Escuela Profesional de Ingeniera de Sistemas

Curso

: Sistemas Distribuidos

Tema

: Conexin de socket, Cliente Servidor

Docente

: Ing. Edilberto Aliaga Romayna.

Alumnos

: Garca Acosta Gino Anderson


Pea Linares Giezi Miguel
Lozano Garca Oscar
Puyo Torres Lennin Heison
Arana Tello Jose G
Trujillo Silvano Rony Aderly

Ciclo

: VIII

PROGRAMACION DE SOCKET CON JAVA Y MYSQL

Un socket es un punto final de un proceso de comunicacin. Es una abstraccin


que permite manejar de una forma sencilla la comunicacin entre procesos,
aunque estos procesos se encuentren en sistemas distintos, sin necesidad de
conocer el funcionamiento de los protocolos de comunicacin subyacentes.
Los mecanismos de comunicacin entre procesos pueden tener lugar dentro de
la misma mquina o a travs de una red. Generalmente son usados en forma de
cliente-servidor, es decir, cuando un cliente y un servidor establecen una
conexin, lo hacen a travs de un socket.
Bsicamente, este es el funcionamiento de los Socket que necesitamos para una
conexin TCP. En el que podemos distinguir dos tipos de Socket el del Servidor
y el del Cliente.
La creacin del socket en el servidor se remite a crear el socket, indicar porque
puerto se harn las escuchas y esperar a la llamada de un cliente para aceptar
la conexin, en cambio un cliente crear el socket e indicar donde se encuentra
y por qu puerto quiere conectarse, de esta forma Cliente y Servidor crearn una
conexin.
Servidor
Para crear los socket se crea un objeto del tipo ServerSocket, este mtodo
pertenece a la clase java.net.Serversocket
Una vez que hemos creado el objeto socket mandamos un parmetro que
indicar el puerto por el que se realzar las comunicaciones.
Para realizar una conexin entre Cliente-Servidor, el servidor usar el mtodo
socket.accept para confirmar que se ha iniciado la conexin.

Cliente
Primero crea un objeto del tipo Socket que pertenece a la clase
java.net.Serversocket, despus se obtiene un objeto InetAddress, y usando el
mtodo getByName le indicamos donde se va a ejecutar el cliente, en nuestro
caso indicamos que ser en localhost.
Finalmente creamos un objeto de tipo socket al que pasaremos la direccin
donde se est ejecutando el cliente, y el puerto por donde se conectar al
servidor.

Primero se comenzara con la parte del cliente:


CLASE bdManager
Para establecer la conexin con MysqlWorbench:
package distribuidos_socket;

import java.sql.Connection;
import java.sql.DriverManager;
public class dbManager {
private

final

String

url="jdbc:mysql://localhost:3306/chat?zeroDateTimeBehavior=convertToN
ull";
private final String driver="com.mysql.jdbc.Driver";
private final String user="root";

private final String pass="miguel";


private String error;
public String getError()
{
return error;
}
public Connection getConnection(){
error = null;
try{
Class.forName(driver);
return (DriverManager.getConnection(url,user,pass));
}catch (Exception e){error.toString();
System.out.println("ERROR DBMANAGER");
System.out.println(e.getMessage());
}
return null;
}
public void closeConnection(Connection con){
error = null;
try{

con.close();
}catch (Exception e){error=e.toString();}
}
}
CLASE inicio:
package distribuidos_socket;

import javax.swing.JOptionPane;
public class inicio {
public static usuario nv;
public static void main(String[] args) {
NewJFrame.cliObje.setIpUsuario(
JOptionPane.showInputDialog("Ingrese su IP:"));
NewJFrame.cliObje.setNick(JOptionPane.showInputDialog("Ingrese
su Nick"));
new NewJFrame().setVisible(true);
}
Para la parte del cliente se le pedir que ingrese una ip valida:

Luego un nombre (Nick):

CLASE cliente
package distribuidos_socket;
import java.io.Serializable;
public class Cliente implements Serializable{
private String nick;
private String ip;
private String mensaje;
public String getNick() {
return nick;
}
public void setNick(String nick) {
this.nick = nick;

}
public String getIp() {
return ip;
}
public void setIp(String ip) {
this.ip = ip;
}
public String getMensaje() {
return mensaje;
}
public void setMensaje(String mensaje) {
this.mensaje = mensaje;
}
}

Para despus se mostrara la siguiente interfaz:

package distribuidos_socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class NewJFrame extends javax.swing.JFrame implements Runnable {
/**
* Creates new form NewJFrame
*/
public NewJFrame() {
initComponents();
Thread hilo=new Thread(this);
hilo.start();

}
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();


djfhdjfd = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
txtNick = new javax.swing.JTextField();
txtIp = new javax.swing.JTextField();
txtMensaje = new javax.swing.JTextField();
jScrollPane1 = new javax.swing.JScrollPane();
txtMensajes = new javax.swing.JTextArea();
btnEnviar = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

djfhdjfd.setText("Nick");
jLabel2.setText("Ip");
jLabel3.setText("Mensaje");
txtMensajes.setColumns(20);

txtMensajes.setRows(5);
jScrollPane1.setViewportView(txtMensajes);
btnEnviar.setText("Enviar");
btnEnviar.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnEnviarActionPerformed(evt);
}
});
btnEnviar.addKeyListener(new java.awt.event.KeyAdapter() {
public void keyPressed(java.awt.event.KeyEvent evt) {
btnEnviarKeyPressed(evt);
}
public void keyTyped(java.awt.event.KeyEvent evt) {
btnEnviarKeyTyped(evt);
}
});
jButton1.setText("Limpiar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);

}
});
javax.swing.GroupLayout

jPanel1Layout

new

javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.
Alignment.LEADING)
.addComponent(jButton1)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.LEADING, false)
.addComponent(jScrollPane1,

javax.swing.GroupLayout.PREFERRED_SIZE,

392, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(jPanel1Layout.createSequentialGroup()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.LEADING)

.addComponent(djfhdjfd)
.addComponent(jLabel3)
.addComponent(jLabel2,
javax.swing.GroupLayout.PREFERRED_SIZE,

10,

javax.swing.GroupLayout.PREFERRED_SIZE))
.addGap(39, 39, 39)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.LEADING, false)
.addComponent(txtNick)
.addComponent(txtIp)
.addComponent(txtMensaje,
javax.swing.GroupLayout.DEFAULT_SIZE, 181, Short.MAX_VALUE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(btnEnviar))))
.addContainerGap(36, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)
.addGroup(jPanel1Layout.createSequentialGroup()

.addGap(20, 20, 20)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.BASELINE)
.addComponent(djfhdjfd)
.addComponent(txtNick,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE))

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATE
D)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.BASELINE)
.addComponent(txtIp,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2))
.addGap(18, 18, 18)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.TRAILING)
.addComponent(jLabel3)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.BASELINE)
.addComponent(txtMensaje,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(btnEnviar)))
.addGap(26, 26, 26)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE,

146,

javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATE
D)
.addComponent(jButton1)
.addContainerGap(19, Short.MAX_VALUE))
);

javax.swing.GroupLayout

layout

javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

new

.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);

pack();
}// </editor-fold>

private void btnEnviarActionPerformed(java.awt.event.ActionEvent evt) {


if(evt.getSource()==btnEnviar){
try{
Socket cliente=new Socket("192.168.1.36",9081);

Cliente cliObj=new Cliente();


cliObj.setNick(txtNick.getText());
cliObj.setIp(txtIp.getText());
cliObj.setMensaje(txtMensaje.getText());
ObjectOutputStream

flujo=new

ObjectOutputStream(cliente.getOutputStream());
flujo.writeObject(cliObj);
cliente.close();
} catch (Exception ex){
System.out.println(ex.getMessage());
}
}
}

private void btnEnviarKeyPressed(java.awt.event.KeyEvent evt) {


}
private void btnEnviarKeyTyped(java.awt.event.KeyEvent evt) {
// TODO add your handling code here:
}
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
txtIp.setText(null);

txtMensaje.setText(null);
txtMensajes.setText(null);
txtNick.setText(null);

}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default
look and feel.
*

For

details

see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for

(javax.swing.UIManager.LookAndFeelInfo

info

javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}

} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(NewJFrame.class.getName()).log(java.util.lo
gging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrame().setVisible(true);

});
}
// Variables declaration - do not modify
private javax.swing.JButton btnEnviar;
private javax.swing.JLabel djfhdjfd;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextField txtIp;
private javax.swing.JTextField txtMensaje;
private static javax.swing.JTextArea txtMensajes;
private javax.swing.JTextField txtNick;
// End of variables declaration
@Override
public void run() {
try {
ServerSocket serv=new ServerSocket(9090);
Socket cliente;

Cliente cliObj;
while(true)
{
cliente=serv.accept();
ObjectInputStream

flujo=new

ObjectInputStream(cliente.getInputStream());
cliObj=(Cliente)flujo.readObject();
txtMensajes.append("\n

"+cliObj.getNick()+":

\n

"+cliObj.getMensaje());
cliente.close();
}

} catch (IOException | ClassNotFoundException e) {


System.err.println("Error en recibir datos de servidor en cliente
"+e.getMessage());
}
}
}

Clase conversacin
package distribuidos_socket;

import java.util.ArrayList;
import java.util.Calendar;
public class Conversacion {

private Calendar fecha;


private ArrayList <usuario> usuarios;

public Calendar getFecha() {


return fecha;
}

public void setFecha(Calendar fecha) {


this.fecha = fecha;
}

public ArrayList <usuario> getUsuarios() {


return usuarios;
}

public void setUsuarios(ArrayList <usuario> usuarios) {


this.usuarios = usuarios;
}

public void date(){


fecha.getTime().toLocaleString();
}
}

Para el servidor:

package distribuidos_socket;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class NewJFrameServer extends javax.swing.JFrame implements


Runnable{

ServerSocket serv=null;
public NewJFrameServer() {
initComponents();

Thread hilo=new Thread(this);


hilo.start();
}

@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {

jPanel1 = new javax.swing.JPanel();


jScrollPane1 = new javax.swing.JScrollPane();
txtMensaje = new javax.swing.JTextArea();
jLabel1 = new javax.swing.JLabel();
btnSalir = new javax.swing.JButton();
jButton1 = new javax.swing.JButton();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

txtMensaje.setColumns(20);
txtMensaje.setRows(5);
jScrollPane1.setViewportView(txtMensaje);

jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N


jLabel1.setText("SERVIDOR");

btnSalir.setText("Salir");
btnSalir.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btnSalirActionPerformed(evt);
}
});

jButton1.setText("Limpiar");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);

}
});

javax.swing.GroupLayout

jPanel1Layout

new

javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)
.addGroup(jPanel1Layout.createSequentialGroup()
.addContainerGap()

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(btnSalir))
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(139, 139, 139)

369,

.addComponent(jLabel1))
.addComponent(jButton1))
.addContainerGap(41, Short.MAX_VALUE))
);
jPanel1Layout.setVerticalGroup(

jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADI
NG)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(25, 25, 25)

.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Align
ment.TRAILING)
.addComponent(btnSalir)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(jLabel1)
.addGap(18, 18, 18)
.addComponent(jScrollPane1,
javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGap(18, 18, 18)
.addComponent(jButton1)
.addContainerGap(19, Short.MAX_VALUE))

249,

);

javax.swing.GroupLayout

layout

new

javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())
);
layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addContainerGap())

);

pack();
}// </editor-fold>

private void btnSalirActionPerformed(java.awt.event.ActionEvent evt) {


if(evt.getSource()==btnSalir)
{
try {
serv.close();
dispose();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {

txtMensaje.setText(null);

}
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code
(optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default
look and feel.
*

For

details

see

http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for

(javax.swing.UIManager.LookAndFeelInfo

info

javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {

java.util.logging.Logger.getLogger(NewJFrameServer.class.getName()).log(java
.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {

java.util.logging.Logger.getLogger(NewJFrameServer.class.getName()).log(java
.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {

java.util.logging.Logger.getLogger(NewJFrameServer.class.getName()).log(java
.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {

java.util.logging.Logger.getLogger(NewJFrameServer.class.getName()).log(java
.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new NewJFrameServer().setVisible(true);
}
});
}

// Variables declaration - do not modify


private javax.swing.JButton btnSalir;

private javax.swing.JButton jButton1;


private javax.swing.JLabel jLabel1;
private javax.swing.JPanel jPanel1;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextArea txtMensaje;
// End of variables declaration

@Override
public void run() {
try{
serv= new ServerSocket(9083);
String nick,ip,mensaje;
Socket cli;
usuario CliObj;

while(true){
cli=serv.accept();
ObjectInputStream flujo=new ObjectInputStream(cli.getInputStream());
CliObj=(usuario) flujo.readObject();
nick=CliObj.getNick();

ip=CliObj.getIpUsuario();
mensaje=CliObj.getMensaje();
txtMensaje.append("\n

"+nick+"

Le

dice

a:

"+ip+"\n

Mensaje:

"+mensaje);
Socket cliEnvia=new Socket(ip,9082);
ObjectOutputStream
ObjectOutputStream(cliEnvia.getOutputStream());
flujoEnvia.writeObject(CliObj);
cli.close();
}

}catch(IOException | ClassNotFoundException ex){


System.out.println("Error en servidor"+ex.getMessage());
}
}
}

flujoEnvia=new

Y luego enva al receptor al mismo tiempo el mensaje enviado del receptor sale
en su text rea (mensaje), la cual se mostrar en el panel del cliente:

El gestor para la base de datos que se utilizo fue MysqlWorbench:

El nombre de la base de datos se llama: chat, crendose una tabla llamada


usuario, dentro de las cuales las columnas son:

IpUsuario varchar(20)

IpRecepcion

Puerto

Nick varchar(20)

Mensaje varchar(244)

Fecha varchar(45)

Como en este caso se envi a si mismo sale mensaje enviado y mensaje


recibido, luego para verificar que los datos fueron almacenados, nos dirigimos a
la base de datos, realizado en MysqlWorbench y se proceder hacer una
consulta:
Select * from chat.usuario;

Anda mungkin juga menyukai