whiplk

[App] - TCPClient.java

Sep 3rd, 2013
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.73 KB | None | 0 0
  1. //TCP - Cliente.java, Willian Luigi (c) CODE.ME
  2. //Tutorial de conexão TCP: http://codeme.forumeiros.com/t40-conexao-tcpservidor-cliente#245
  3.  
  4. import java.io.*;
  5. import java.net.*;
  6. import java.awt.*;
  7. import java.awt.event.*;
  8. import java.util.*;
  9. import javax.swing.*;
  10.  
  11. class Usuario extends JFrame {
  12.     JButton conectar = new JButton("Enviar");
  13.     JTextField txbMsg = new JTextField();
  14.     JLabel lbl = new JLabel("");
  15.     public Usuario() {
  16.         super ("Setting up a connection, (C)CODE.ME");
  17.         conectar.setBounds(240, 30, 70, 30);
  18.         txbMsg.setBounds(10, 30, 200, 30);
  19.         lbl.setBounds(15, 60, 200, 15);
  20.         this.getContentPane().setLayout(null);
  21.         this.getContentPane().add(conectar);
  22.         this.getContentPane().add(txbMsg);
  23.         this.getContentPane().add(lbl);
  24.         try {
  25.             eventoBtn(conectar);
  26.         } catch (Exception e) {
  27.         }
  28.         setSize(340, 120);
  29.         setVisible(true);
  30.         setIconImage(new ImageIcon("fav.png").getImage());
  31.     }
  32.    
  33.     public void eventoBtn(JButton v) {     
  34.         ActionListener click = new ActionListener() {
  35.             public void actionPerformed(ActionEvent e) {
  36.                 try {
  37.                     lbl.setText(conectar(txbMsg.getText()));
  38.                 } catch (Exception o) {
  39.                    
  40.                 }      
  41.             }
  42.         };
  43.        
  44.         v.addActionListener(click);
  45.     }
  46.    
  47.     public static void main(String[] args) {
  48.         new Usuario();
  49.     }
  50.    
  51.     public String conectar(String msg) throws Exception {
  52.         String resposta;
  53.         Socket client = new Socket("127.0.0.1", 7777);
  54.         DataOutputStream toSv = new DataOutputStream(client.getOutputStream());
  55.         BufferedReader bufferSv = new BufferedReader(new InputStreamReader(client.getInputStream()));
  56.         toSv.writeBytes(msg + '\n');
  57.         resposta = bufferSv.readLine();
  58.         System.out.println("Servidor: " + resposta);
  59.         client.close();
  60.         return "Servidor: " + resposta;
  61.     }
  62. }
Advertisement
Add Comment
Please, Sign In to add comment