SOCKET聊天客户端

来源:互联网 发布:好的网络宣传方式 编辑:程序博客网 时间:2024/04/30 11:01

 

Code:
  1. import java.io.*;  
  2. import java.net.*;  
  3.   
  4. import javax.swing.*;  
  5. import java.awt.*;  
  6. import java.awt.event.*;  
  7.   
  8. public class SimpleChatClientA {  
  9.   
  10.     /** 
  11.      * @param args 
  12.      */  
  13.     JTextField outgoing;  
  14.     PrintWriter writer;  
  15.     Socket sock;  
  16.       
  17.     public void go(){  
  18.         JFrame frame = new JFrame("JAVA聊天BATA0.5");  
  19.         JPanel mainPanel = new JPanel();  
  20.         outgoing = new JTextField(20);  
  21.         JButton sendButton = new JButton("send");  
  22.         sendButton.addActionListener(new SendButtonListener());  
  23.         mainPanel.add(outgoing);  
  24.         mainPanel.add(sendButton);  
  25.         JLabel label = new JLabel("徐方鑫:280599580@qq.com");  
  26.         mainPanel.add(label);  
  27.         frame.getContentPane().add(BorderLayout.CENTER,mainPanel);  
  28.         setUpNetworking();  
  29.         frame.setSize(400,100);  
  30.         frame.setVisible(true);  
  31.     }  
  32.     public void setUpNetworking(){  
  33.         try{  
  34.             sock = new Socket("222.95.182.107",5000);  
  35.             writer = new PrintWriter(sock.getOutputStream());  
  36.             System.out.println("networking established");  
  37.         }catch(IOException ex)  
  38.         {  
  39.             ex.printStackTrace();  
  40.         }  
  41.               
  42.     }  
  43.     public class SendButtonListener implements ActionListener{  
  44.         public void actionPerformed(ActionEvent ev){  
  45.             try{  
  46.                 writer.println(outgoing.getText());  
  47.                 writer.flush();  
  48.             }catch(Exception ex)  
  49.             {  
  50.                 ex.printStackTrace();  
  51.             }  
  52.             outgoing.setText("");  
  53.             outgoing.requestFocus();  
  54.         }  
  55.     }  
  56.     public static void main(String[] args) {  
  57.         // TODO Auto-generated method stub  
  58.         new SimpleChatClientA().go();  
  59.     }  
  60.   
  61. }  

 

原创粉丝点击