Envio de Mensagem Client-Serv usando Socket

4 respostas
J

Eu tenho um codigo exemplo que faz o envio de pacotes entre um cliente e um servidor, mas para ser enviada a mensagem é necessario ser teclado ENTER na JTextField. Gostaria que assim que fosse executada a classe client essa mensagem ja fosse enviada. Já tentei tirar o escutador de eventos da JTextField, mas NullPointerException. Como poderia resolver esse problema ???

// Client.java
// Client that sends and receives packets to/from a server.
import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client extends JFrame {
   private JTextField enterField;
   private JTextArea displayArea;
   private DatagramSocket socket;

   
   // set up GUI and DatagramSocket
   public Client()
   {
     // super( "Client" );

      Container container = getContentPane();

      enterField = new JTextField();
      enterField.addActionListener(
         new ActionListener() { 
            public void actionPerformed( ActionEvent event )
           {
               // create and send packet
               try {
                 
                  String relatorio = "Lindeberg Pessoa Leite"; 
                  byte data[] = relatorio.getBytes();
         
                  // create sendPacket
                  DatagramPacket sendPacket = new DatagramPacket( data, 
                     data.length, InetAddress.getLocalHost(), 5000 );

                  socket.send( sendPacket ); // send packet
               }

               // process problems creating or sending packet
               catch ( IOException ioException ) {
                  ioException.printStackTrace();
               }

            } // end actionPerformed

        } // end inner class

      ); // end call to addActionListener

     container.add( enterField, BorderLayout.NORTH );

      setSize( 400, 300 );
      setVisible( true );

      // create DatagramSocket for sending and receiving packets
      try {
         socket = new DatagramSocket();
      }

      // catch problems creating DatagramSocket
      catch( SocketException socketException ) {
         socketException.printStackTrace();
         System.exit( 1 );
      }

   } // end Client constructor

   public static void main( String args[] )
   {
      
      
      Client application = new Client();
     // application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );

   }

}  // end class Client
// Fig. 18.6: Server.java
// Server that receives and sends packets from/to a client.

import java.io.*;
import java.net.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Server extends JFrame {
   private JTextArea displayArea;
   private DatagramSocket socket;


   // set up GUI and DatagramSocket
   public Server()
   {
      super( "Server" );

      displayArea = new JTextArea();
      getContentPane().add( new JScrollPane( displayArea ),
         BorderLayout.CENTER );
      setSize( 400, 300 );
      setVisible( true );

      // create DatagramSocket for sending and receiving packets
      try {
         socket = new DatagramSocket( 5000 );
      }

      // process problems creating DatagramSocket
      catch( SocketException socketException ) {
         socketException.printStackTrace();
         System.exit( 1 );
      }

   } // end Server constructor

   // wait for packets to arrive, display data and echo packet to client
   private void waitForPackets()
   {
      while ( true ) { // loop forever

         // receive packet, display contents, return copy to client
         try {

            // set up packet
            byte data[] = new byte[ 100 ];
            DatagramPacket receivePacket = 
               new DatagramPacket( data, data.length );
//			DatagramPacket receivePacket = 
	//					 new DatagramPacket( resultado);

            socket.receive( receivePacket ); // wait for packet

            // display information from received packet 
            displayMessage( "\nPacket received:" + 
               "\nFrom host: " + receivePacket.getAddress() + 
               "\nHost port: " + receivePacket.getPort() + 
               "\nLength: " + receivePacket.getLength() + 
               "\nContaining:\n\t" + new String( receivePacket.getData(), 
                  0, receivePacket.getLength() ) );

           
           
            sendPacketToClient( receivePacket ); // send packet to client
         }

         // process problems manipulating packet
         catch( IOException ioException ) {
            displayMessage( ioException.toString() + "\n" );
            ioException.printStackTrace();
         }

      } // end while

   } // end method waitForPackets

   // echo packet to client
   private void sendPacketToClient( DatagramPacket receivePacket ) 
 	
      throws IOException
   {
      displayMessage( "\n\nEcho data to client..." );

      // create packet to send
	     
      DatagramPacket sendPacket = new DatagramPacket
      ( receivePacket.getData(), receivePacket.getLength(), 
         receivePacket.getAddress(), receivePacket.getPort());
 
      socket.send( sendPacket ); // send packet
      displayMessage( "Packet sent\n" );
   }

   // utility method called from other threads to manipulate 
   // displayArea in the event-dispatch thread
   private void displayMessage( final String messageToDisplay )
   {
      // display message from event-dispatch thread of execution
      SwingUtilities.invokeLater(
         new Runnable() {  // inner class to ensure GUI updates properly

            public void run() // updates displayArea
            {
               displayArea.append( messageToDisplay );
               displayArea.setCaretPosition( 
                  displayArea.getText().length() );
            }

         }  // end inner class

      ); // end call to SwingUtilities.invokeLater
   }

   public static void main( String args[] )
   {
      Server application = new Server();
      application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
      application.waitForPackets();
   }

} // end class Server

4 Respostas

_fs

Quando você recebe a NullPointerException? Em que linha?

J

Quando eu tiro o escutador de eventos do TextField ele da a NullPointerException nesta linha: socket.send( sendPacket ); // send packet .

Lucas_Teixeira

Voce apenas declara a referencia

private DatagramSocket socket;

e ja usa logo em seguida:

socket.send(...)

antes de usar vc deve atribuir outra referencia a ela, ou intanciar, ou entao qualquer coisa que diga a teu sistema que ela não é nula (aí o porque da NullPointer)

rsantini

Olá javax,

:wink: gostaria de utilizar essa sua implementação de sockets, para fazer uma determinada comunicação entre máquinas, mas peguei o seu exemplo e não consegui! somente consigo se for da minha própria máquina, sou iniciante em Java, portanto sinto dificuldades ainda na codificação, será que alguém poderia me ajudar ?

Obrigado.

Criado 4 de janeiro de 2005
Ultima resposta 10 de fev. de 2005
Respostas 4
Participantes 4