java 图形界面 Socket编程

一、使用图形界面实现客户端服务器端的通信:

上代码:

服务器端代码:

package cn.MyNET;

import java.io.*;
import java.net.*;
import java.util.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class Server2 extends JFrame{
    //输入消息框
    private JTextField jtf = new JTextField();
    //显示框
    private JTextArea jta = new JTextArea();
    //IO流
    private DataInputStream inputFromClient;
    private DataOutputStream outputToClient;
    
    public static void main(String[] args){
        new Server2();
    }
    
    public Server2(){
        JPanel p = new JPanel();
        p.setLayout(new BorderLayout());
        p.add(new JLabel("请输入消息"), BorderLayout.WEST);
        p.add(jtf, BorderLayout.CENTER);
        jtf.setHorizontalAlignment(JTextField.RIGHT);    //设置对齐方式
        
        setLayout(new BorderLayout());
        add(p, BorderLayout.NORTH);
        add(new JScrollPane(jta), BorderLayout.CENTER);
        
        jtf.addActionListener(new TextFieldListener());
        
        setTitle("Server");
        setSize(500, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        
        try {
            ServerSocket serverSocket = new ServerSocket(8000);
            jta.append("服务器已启动~~    启动时间:" + new Date() +'\n');
            
            //监听连接请求
            Socket socket = serverSocket.accept();
            //IO流
            inputFromClient = new DataInputStream(socket.getInputStream());
            outputToClient = new DataOutputStream(socket.getOutputStream());
            
            //获取客户端的名称 和 IP
            InetAddress inetAddress = socket.getInetAddress();
            String clientName = inetAddress.getHostName();
            String clientIP = inetAddress.getHostAddress();
            while(true){
                String fromClient = inputFromClient.readUTF();
                jta.append("客户端" + clientName + ";  " + clientIP + "发来消息: "+fromClient);
            }
        } catch (IOException e) {
            System.out.println(e);
        }
    }
    
    private class TextFieldListener implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                outputToClient.writeUTF(jtf.getText().trim() + '\n');    //向服务器发送消息
                jta.append("发送的消息:" + jtf.getText().trim() +'\n');
                jtf.setText("");        //输出后清空输入框
                
            } catch (IOException e1) {
                System.err.println(e1);
            }
            
        }
    }
}
服务器端

 客户端代码:

package cn.MyNET;


import java.io.*;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Client2 extends JFrame {
    //输入消息框
    private JTextField jtf = new JTextField();
    //显示区域
    private JTextArea jta = new JTextArea();
    //IO流
    private DataOutputStream toServer;
    private DataInputStream fromServer;
    
    public static void main(String[] args){
        new Client2();
    }
    
    public Client2(){
        JPanel p = new JPanel();
        p.setLayout(new BorderLayout());
        p.add(new JLabel("请输入消息"), BorderLayout.WEST);
        p.add(jtf, BorderLayout.CENTER);
        jtf.setHorizontalAlignment(JTextField.RIGHT);
        
        setLayout(new BorderLayout());
        add(p, BorderLayout.NORTH);
        add(new JScrollPane(jta), BorderLayout.CENTER);
        
        jtf.addActionListener(new TextFieldListener());
        
        setTitle("Client");
        setSize(500, 300);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setVisible(true);
        try {
            
            Socket socket = new Socket("localhost", 8000);
            
            fromServer = new DataInputStream(socket.getInputStream());
            
            toServer = new DataOutputStream(socket.getOutputStream());
            
            while(true){
            String fromStr = fromServer.readUTF();
            jta.append("服务端发来消息:" +fromStr);
            }
        } catch (IOException e) {
            jta.append(e.toString() + '\n');
        }
    }
    
    private class TextFieldListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {
            try {
                //得到当前时间
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //  设置日期格式
                String time = df.format(Calendar.getInstance().getTime());      //得到时间
                toServer.writeUTF(jtf.getText().trim() + '\n');    //向服务器发送消息
                jta.append( time + "发送的消息:" + jtf.getText().trim() +'\n');
                jtf.setText("");        //输出后清空输入框
                
            } catch (IOException e1) {
                System.err.println(e1);
            }
        }
    }
}
客户端代码

 

 运行效果:

 

二、图形界面升级版,可以设置端口。

使用时必须先开启服务端,建立连接,然后客户端进行连接。

Server:

  1 package cn.MyNET;
  2 
  3 import java.awt.EventQueue;
  4 
  5 import javax.swing.JFrame;
  6 import javax.swing.JPanel;
  7 import javax.swing.border.EmptyBorder;
  8 
  9 import javax.swing.JLabel;
 10 import javax.swing.JTextField;
 11 import javax.swing.JButton;
 12 import javax.swing.JTextArea;
 13 import java.awt.Color;
 14 import java.awt.event.ActionListener;
 15 import java.io.DataInputStream;
 16 import java.io.DataOutputStream;
 17 import java.io.IOException;
 18 import java.net.InetAddress;
 19 import java.net.ServerSocket;
 20 import java.net.Socket;
 21 import java.util.Date;
 22 import java.awt.event.ActionEvent;
 23 
 24 public class Server3_GUI extends JFrame {
 25 
 26     private JPanel contentPane;
 27     private JTextField textField;
 28     private JTextField txtXiaoXi;
 29     private JTextArea textMessage;
 30     
 31     //IO流
 32     private DataInputStream inputFromClient;
 33     private DataOutputStream outputToClient;
 34 
 35     ServerSocket serverSocket;
 36     Socket socket;
 37     
 38     /**
 39      * Launch the application.
 40      */
 41     public static void main(String[] args) {
 42         EventQueue.invokeLater(new Runnable() {
 43             public void run() {
 44                 try {
 45                     Server3_GUI frame = new Server3_GUI();
 46                     frame.setVisible(true);
 47                 } catch (Exception e) {
 48                     e.printStackTrace();
 49                 }
 50             }
 51         });
 52     }
 53 
 54     /**
 55      * Create the frame.
 56      */
 57     public Server3_GUI() {
 58         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 59         setBounds(100, 100, 450, 300);
 60         contentPane = new JPanel();
 61         contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
 62         setContentPane(contentPane);
 63         contentPane.setLayout(null);
 64         
 65         JPanel panel = new JPanel();
 66         panel.setBounds(0, 0, 426, 57);
 67         contentPane.add(panel);
 68         panel.setLayout(null);
 69         
 70         JLabel label = new JLabel("端口:");
 71         label.setBounds(12, 12, 39, 15);
 72         panel.add(label);
 73         
 74         textField = new JTextField();
 75         textField.setText("8000");
 76         textField.setBounds(55, 10, 50, 19);
 77         panel.add(textField);
 78         textField.setColumns(10);
 79         
 80         JButton button = new JButton("启动");
 81         button.setBounds(200, 7, 70, 25);
 82         panel.add(button);
 83         button.addActionListener(new buttonListener());
 84         
 85         JButton button_1 = new JButton("停止");
 86         button_1.addActionListener(new ActionListener() {
 87             public void actionPerformed(ActionEvent e) {
 88                 try {
 89                     inputFromClient.close();
 90                     outputToClient.close();
 91                     socket.close();
 92                     textMessage.append("连接已断开~~~");
 93                 } catch (Exception e2) {
 94                     // TODO: handle exception
 95                 }
 96             }
 97         });
 98         button_1.setBounds(300, 7, 70, 25);
 99         panel.add(button_1);
100         
101         JPanel panel_1 = new JPanel();
102         panel_1.setBounds(0, 69, 416, 170);
103         contentPane.add(panel_1);
104         
105         textMessage = new JTextArea();
106         textMessage.setTabSize(4);
107         textMessage.setRows(11);
108         textMessage.setColumns(35);
109         textMessage.setBackground(Color.LIGHT_GRAY);
110         textMessage.setText("123");
111         panel_1.add(textMessage);
112         
113         JPanel panel_2 = new JPanel();
114         panel_2.setBounds(10, 240, 428, 89);
115         contentPane.add(panel_2);
116         panel_2.setLayout(null);
117         
118         txtXiaoXi = new JTextField();
119         txtXiaoXi.addActionListener(new sendListener());
120         txtXiaoXi.setBounds(12, 5, 300, 25);
121         panel_2.add(txtXiaoXi);
122         txtXiaoXi.setColumns(10);
123         
124         JButton button_2 = new JButton("发送");
125         button_2.setBounds(324, 5, 70, 25);
126         panel_2.add(button_2);
127         
128         button_2.addActionListener(new sendListener());
129     }
130     
131     private class sendListener implements ActionListener{
132         @Override
133         public void actionPerformed(ActionEvent e) {
134             try {
135                 outputToClient.writeUTF(txtXiaoXi.getText().trim() + '\n');    //向服务器发送消息
136                 textMessage.append("发送的消息:" + txtXiaoXi.getText().trim() +'\n');
137                 txtXiaoXi.setText("");        //输出后清空输入框
138                 
139             } catch (IOException e1) {
140                 System.err.println(e1);
141             }
142         }
143     }
144     
145     
146     private class buttonListener implements ActionListener{
147         @Override
148         public void actionPerformed(ActionEvent e) {
149             int port = Integer.parseInt(textField.getText());
150              try {
151                  serverSocket = new ServerSocket(port);
152                 textMessage.append("服务器已启动~~    启动时间:" + new Date() +'\n');
153                 
154                 //监听连接请求
155                 socket = serverSocket.accept();
156                 textMessage.append("连接成功~~~" + '\n');
157                 Server_thread server3_thread = new Server_thread();
158                 Thread thread = new Thread(server3_thread);
159                 thread.start();
160             } catch (IOException e1) {
161                 System.out.println(e1);
162             }
163         }
164     }
165     
166     //输入输出线程
167     private class Server_thread implements Runnable{
168         public Server_thread(){
169             
170         }
171         public void run(){
172             try {
173                 //IO流
174                 inputFromClient = new DataInputStream(socket.getInputStream());
175                 outputToClient = new DataOutputStream(socket.getOutputStream());
176                 //获取客户端的名称 和 IP
177                 InetAddress inetAddress = socket.getInetAddress();
178                 String clientName = inetAddress.getHostName();
179                 String clientIP = inetAddress.getHostAddress();
180                 while(true){
181                 String fromClient = inputFromClient.readUTF();
182                 textMessage.append("客户端" + clientName + ";  " + clientIP + "发来消息: "+fromClient);
183                 }
184             } catch (IOException e) {
185                 e.printStackTrace();
186             }
187         }
188     }
189 }
View Code

 

Client:

  1 package cn.MyNET;
  2 
  3 import java.awt.Color;
  4 import java.awt.EventQueue;
  5 
  6 import javax.swing.JFrame;
  7 import javax.swing.JPanel;
  8 import javax.swing.border.EmptyBorder;
  9 
 10 import javax.swing.JLabel;
 11 import javax.swing.JTextField;
 12 import javax.swing.JButton;
 13 import javax.swing.JTextArea;
 14 import java.awt.event.ActionListener;
 15 import java.io.DataInputStream;
 16 import java.io.DataOutputStream;
 17 import java.io.IOException;
 18 import java.net.Socket;
 19 import java.text.SimpleDateFormat;
 20 import java.util.Calendar;
 21 import java.awt.event.ActionEvent;
 22 
 23 public class Client3_GUI extends JFrame {
 24 
 25     private JPanel contentPane;
 26     private JTextField textField_IP;
 27     private JTextField textField_Port;
 28     private JTextField txtXiaoxi;
 29     
 30     //IO流
 31     private DataOutputStream toServer;
 32     private DataInputStream fromServer;
 33     JTextArea txtMessage;
 34     Socket socket;
 35     /**
 36      * Launch the application.
 37      */
 38     public static void main(String[] args) {
 39         EventQueue.invokeLater(new Runnable() {
 40             public void run() {
 41                 try {
 42                     Client3_GUI frame = new Client3_GUI();
 43                     frame.setVisible(true);
 44                 } catch (Exception e) {
 45                     e.printStackTrace();
 46                 }
 47             }
 48         });
 49     }
 50 
 51     /**
 52      * Create the frame.
 53      */
 54     public Client3_GUI() {
 55         setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 56         setBounds(100, 100, 450, 300);
 57         contentPane = new JPanel();
 58         contentPane.setToolTipText("Client");
 59         contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
 60         setContentPane(contentPane);
 61         contentPane.setLayout(null);
 62         
 63         JPanel panel = new JPanel();
 64         panel.setBounds(12, 5, 415, 100);
 65         contentPane.add(panel);
 66         panel.setLayout(null);
 67         
 68         JLabel lblip = new JLabel("服务器IP:");
 69         lblip.setBounds(12, 12, 65, 15);
 70         panel.add(lblip);
 71         
 72         textField_IP = new JTextField();
 73         textField_IP.setText("localhost");
 74         textField_IP.setBounds(82, 10, 114, 19);
 75         panel.add(textField_IP);
 76         textField_IP.setColumns(10);
 77         
 78         JLabel label = new JLabel("端口:");
 79         label.setBounds(214, 12, 49, 15);
 80         panel.add(label);
 81         
 82         textField_Port = new JTextField();
 83         textField_Port.setText("8000");
 84         textField_Port.setBounds(265, 10, 114, 19);
 85         panel.add(textField_Port);
 86         textField_Port.setColumns(10);
 87         
 88         JButton button = new JButton("连接");
 89         button.setBounds(80, 50, 80, 20);
 90         panel.add(button);
 91         
 92         JButton button_1 = new JButton("断开");
 93         button_1.addActionListener(new ActionListener() {
 94             public void actionPerformed(ActionEvent e) {
 95                 try {
 96                     toServer.close();
 97                     fromServer.close();
 98                     socket.close();
 99                     txtMessage.append("连接已断开~~~");
100                 } catch (IOException e1) {
101                     // TODO Auto-generated catch block
102                     e1.printStackTrace();
103                 }
104                 
105             }
106         });
107         button_1.setBounds(270, 50, 80, 20);
108         panel.add(button_1);
109         
110         JPanel panel_1 = new JPanel();
111         panel_1.setBounds(12, 100, 415, 118);
112         contentPane.add(panel_1);
113         
114         txtMessage = new JTextArea();
115         txtMessage.setBackground(Color.LIGHT_GRAY);
116         txtMessage.setColumns(35);
117         txtMessage.setRows(10);
118         txtMessage.setTabSize(4);
119         //txtMessage.setText("message");
120         panel_1.add(txtMessage);
121         
122         txtXiaoxi = new JTextField();
123         txtXiaoxi.addActionListener(new sendListener());
124         //txtXiaoxi.setText("xiaoxi");
125         txtXiaoxi.setBounds(20, 245, 300, 25);
126         contentPane.add(txtXiaoxi);
127         txtXiaoxi.setColumns(10);
128         
129         JButton button_2 = new JButton("发送");
130         button_2.addActionListener(new sendListener());
131         button_2.setBounds(330, 245, 60, 25);
132         contentPane.add(button_2);
133         
134         
135         button.addActionListener(new ActionListener() {
136             public void actionPerformed(ActionEvent e) {
137                 String ip = textField_IP.getText();
138                 int port = Integer.parseInt(textField_Port.getText());
139                 
140                 try {
141                     
142                      socket = new Socket(ip, port);
143                     
144                     Client3_thread client3_thread = new Client3_thread();
145                     Thread thread = new Thread(client3_thread);
146                     thread.start();
147                 } catch (IOException e1) {
148                     txtMessage.append(e1.toString() + '\n');
149                 }
150             }
151         });
152         
153     }
154     
155     private class sendListener implements ActionListener{
156         @Override
157         public void actionPerformed(ActionEvent e) {
158             try {
159                 //得到当前时间
160                 SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); //  设置日期格式
161                 String time = df.format(Calendar.getInstance().getTime());      //得到时间
162                 toServer.writeUTF(txtXiaoxi.getText().trim() + '\n');    //向服务器发送消息
163                 txtMessage.append( time + "发送的消息:" + txtXiaoxi.getText().trim() +'\n');
164                 txtXiaoxi.setText("");        //输出后清空输入框
165                 
166             } catch (IOException e1) {
167                 System.err.println(e1);
168             }
169         }
170     }
171     
172     //消息收发线程
173     public class Client3_thread implements Runnable{
174         public void run(){
175             try {
176                 fromServer = new DataInputStream(socket.getInputStream());
177                 
178                 toServer = new DataOutputStream(socket.getOutputStream());
179                 while(true){
180                     String fromStr = fromServer.readUTF();
181                     txtMessage.append("服务端发来消息:" +fromStr);
182                     }
183             } catch (IOException e) {
184                 e.printStackTrace();
185             }
186         }
187     }
188 }
View Code

 

 

运行效果:

服务器端:

 客户端:

 

posted on 2016-05-23 15:03  snail-lb  阅读(3339)  评论(0编辑  收藏  举报