packagesendreceive;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.net.ServerSocket;importjava.net.Socket;importjava.net.UnknownHostException;importjava.util.logging.Level;importjava.util.logging.Logger;importjavax.swing.JOptionPane;publicclassSender_Receiver{publicstaticStringa;publicstaticStringb;publicstaticbyte[]buffer;publicstaticinti;publicstaticintii;DataOutputStreamoutput=null;DataInputStreaminput=null;publicstaticvoidmain(Stringargs[]){try{SocketsocketCliente=newSocket("localhost",80);ServerSocketsocket=newServerSocket(80);Sockets=socket.accept();}catch(IOExceptionioex){JOptionPane.showMessageDialog(null,ioex.getMessage());}}publicstaticvoidsend(){a="Dado de envio!";buffer=a.getBytes();}publicstaticvoidreceiver(){}}
Boa noite/tarde/dia,Estou com uma dúvida
Como que eu faço pra ele enviar e receber a frase da string a;
Então, alguém pode me ensinar? please!!! estou muito viciado em java! Estou querendo fazer isso funcionar mas nao estou entendendo!
Por exemplo, eu procurei na internet, eles dizem que eu tenho que transformar tudo em um array de bytes, isso eu ja fiz!
O que eu não entendo são estes output e input… tipo, como o input vai saber que chegou alguma coisa de fora?
V
ViniGodoy
S
SirDominque
Com UDP , eu não preciso pegar o tamanho da mensagem né ? Estou com um pouco de dificuldade pra pegar o tamanho da mensagem!
Vou tentar transportar a palavra “JAVA” e ver o que acontece… em TCP mesmo!
Entao Viny, eu li seu tópico mas estou com dúvida nesta parte:
Para cada arquivo
1 int - Tamanho da string com o nome do diretório
String - Com o nome do diretório.
Tamanho da string = OK , mas por que string + nome do diretório? Não entendo isto de nome do diretório!
String - com nome do diretório???
Vou tentar ver uns videos no youtube enquanto isso!, qualquer coisa eu posto novamente!
S
SirDominque
Ok gente, estou tentando usar printStream mas esta dando erro! Preciso de ajuda!
Quero comecar com algo bem simples pra comecar a aprender TCP e UDP depois!
packagesendreceive;importjava.io.BufferedReader;importjava.io.*;importjava.net.*;importjava.io.DataInputStream;importjava.io.DataOutputStream;importjava.io.IOException;importjava.io.InputStreamReader;importjava.io.PrintStream;importjava.net.ServerSocket;importjava.net.Socket;importjava.net.UnknownHostException;importjava.util.logging.Level;importjava.util.logging.Logger;importjavax.swing.JOptionPane;publicclassReceiver{privatestaticBufferedReaderSS_BF;publicstaticSocketsocket;publicstaticvoidmain()throwsIOException{ServerSocketsocket=newServerSocket(9999);//Esse código abaixo faz travar o programa!SocketSS_Accept=socket.accept();//Eu acho que preciso de um método que substitua esse .accept();//Esse aqui não!SS_BF=newBufferedReader(newInputStreamReader(SS_Accept.getInputStream()));}publicstaticvoidReader()throwsIOException{try{Stringtemp=SS_BF.readLine();}catch(IOExceptionex){System.out.println(ex.getStackTrace());JOptionPane.showMessageDialog(null,ex.getMessage());}}}
packagesendreceive;importjava.io.IOException;importjava.util.logging.Level;importjava.util.logging.Logger;publicclassInterfaceAextendsjavax.swing.JFrame{/** Creates new form InterfaceA */publicInterfaceA(){initComponents();}/** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */@SuppressWarnings("unchecked")// <editor-fold defaultstate="collapsed" desc="Generated Code"> privatevoidinitComponents(){jButton1=newjavax.swing.JButton();jButton2=newjavax.swing.JButton();jButton3=newjavax.swing.JButton();setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);jButton1.setText("Iniciar Servidor");jButton1.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jButton1ActionPerformed(evt);}});jButton2.setText("Iniciar Cliente");jButton2.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jButton2ActionPerformed(evt);}});jButton3.setText("Ler Mensagem");jButton3.addActionListener(newjava.awt.event.ActionListener(){publicvoidactionPerformed(java.awt.event.ActionEventevt){jButton3ActionPerformed(evt);}});javax.swing.GroupLayoutlayout=newjavax.swing.GroupLayout(getContentPane());getContentPane().setLayout(layout);layout.setHorizontalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addContainerGap().addComponent(jButton1).addGap(18,18,18).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addComponent(jButton3).addComponent(jButton2)).addContainerGap(166,Short.MAX_VALUE)));layout.setVerticalGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING).addGroup(layout.createSequentialGroup().addGap(24,24,24).addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE).addComponent(jButton1).addComponent(jButton2)).addGap(18,18,18).addComponent(jButton3).addContainerGap(212,Short.MAX_VALUE)));pack();}// </editor-fold> privatevoidjButton1ActionPerformed(java.awt.event.ActionEventevt){try{Receiver.main();}catch(IOExceptionex){System.out.println(ex.getStackTrace());}}privatevoidjButton3ActionPerformed(java.awt.event.ActionEventevt){Receiver.Reader();// TODO add your handling code here:}privatevoidjButton2ActionPerformed(java.awt.event.ActionEventevt){try{Transport.main();}catch(IOExceptionex){System.out.println(ex.getStackTrace());}}/** * @param args the command line arguments */publicstaticvoidmain(Stringargs[]){/* 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.LookAndFeelInfoinfo:javax.swing.UIManager.getInstalledLookAndFeels()){if("Nimbus".equals(info.getName())){javax.swing.UIManager.setLookAndFeel(info.getClassName());break;}}}catch(ClassNotFoundExceptionex){java.util.logging.Logger.getLogger(InterfaceA.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(InstantiationExceptionex){java.util.logging.Logger.getLogger(InterfaceA.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(IllegalAccessExceptionex){java.util.logging.Logger.getLogger(InterfaceA.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}catch(javax.swing.UnsupportedLookAndFeelExceptionex){java.util.logging.Logger.getLogger(InterfaceA.class.getName()).log(java.util.logging.Level.SEVERE,null,ex);}//</editor-fold>/* Create and display the form */java.awt.EventQueue.invokeLater(newRunnable(){publicvoidrun(){newInterfaceA().setVisible(true);}});}// Variables declaration - do not modify privatejavax.swing.JButtonjButton1;privatejavax.swing.JButtonjButton2;privatejavax.swing.JButtonjButton3;// End of variables declaration }
V
ViniGodoy
O nome do diretório era uma coisa específica do autor do tópico onde expliquei sobre protocolo.
Era o que eu estava explicando no outro tópico, não basta simplesmente sair usando um PrintStream em cima de um socket.
No seu caso, seria talvez um campo inteiro com o id do autor, outro com o tamanho da mensagem e a mensagem em si.
S
SirDominque
Entendi!
Eu preciso estudar mais… Estou vendo aqui umas aulas no youtube!
Assim que eu conseguir alguma coisa, eu posto aqui pra ajudar outros colegas do forum!