Java学习之路0805(基于TCP带有界面的网络通信)

(一)

客户端

public class MyClientRead implements Runnable{
    private MyClient client;
    public MyClientRead(MyClient client){
        this.client=client;
    }
    @Override
    public void run() {
        while(true){
            client.read();
        }
    }
}
客户端界面
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import javax.swing.plaf.basic.DefaultMenuLayout;

import net.sf.json.JSONObject;

public class MyClient extends JFrame {

    private JPanel contentPane;
    private Socket socket;
    private JTextArea textArea;
    private JList list;
    private DefaultListModel<String> modle;
    private JTextArea textArea_1;

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyClient frame = new MyClient();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MyClient() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 819, 598);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        textArea = new JTextArea();
        textArea.setBounds(49, 436, 500, 101);
        contentPane.add(textArea);

        JButton btnNewButton = new JButton("发送");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String msg=createMessage();
                write(msg);
            }
        });
        btnNewButton.setBounds(589, 436, 129, 101);
        contentPane.add(btnNewButton);

        list = new JList();
        list.setBounds(61, 10, 484, 416);
        modle = new DefaultListModel<>();
        list.setModel(modle);
        contentPane.add(list);

        JButton btnNewButton_1 = new JButton("连接服务器");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("连接服务器");
                    socket = new Socket("192.168.0.82", 8080);
                    System.out.println("连接服务器成功");
                    Thread t = new Thread(new MyClientRead(MyClient.this));
                    t.start();
                } catch (UnknownHostException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        });
        btnNewButton_1.setBounds(615, 68, 103, 86);
        contentPane.add(btnNewButton_1);

        textArea_1 = new JTextArea();
        textArea_1.setBounds(578, 268, 178, 36);
        contentPane.add(textArea_1);
    }

    public void read() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = br.readLine();
            modle.addElement("" + line);
            System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 
     * @return 返回一个发送给所有人的信息
     */
    public String createMessage(){
        String msg = textArea.getText();
        JSONObject obj = new JSONObject();
        obj.put("message", msg);
        obj.put("type", "toSingle");
        // 得到时间 Date Calendar Date date=new Date() date.getTime();
        Calendar calendar = Calendar.getInstance();
        long time = calendar.getTimeInMillis();// 得到此时距1970的毫秒数
        obj.put("time", "" + time);
        obj.put("from", socket.getInetAddress().getHostAddress());
        obj.put("to", textArea_1.getText());
        System.out.println(obj.toString());
        return obj.toString();
    }
    /**
     * 将此信息发送给服务器
     * @param msg 即将发送的信息
     */
    public void write(String msg) {
        try {
            OutputStream os=socket.getOutputStream();
            OutputStreamWriter osw=new OutputStreamWriter(os);
            BufferedWriter bw=new BufferedWriter(osw);
            bw.write(msg+"\n");
            bw.flush();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}

服务器

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class MyServerRead implements Runnable {
    private Socket socket;
    private MyServer server;
    public MyServerRead(Socket socket,MyServer server) {
        this.socket=socket;
        this.server=server;
    }

    @Override
    public void run() {
        try {
            InputStream is=socket.getInputStream();//只能读字节
            InputStreamReader isr=new InputStreamReader(is);//读字符
            BufferedReader br=new BufferedReader(isr);//
            while(true){
                String line=br.readLine();
                server.readLine(line);
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
服务器界面
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;

import net.sf.json.JSONObject;

public class MyServer extends JFrame {

    private JPanel contentPane;
    private HashMap<String, Socket> sockets;
    private boolean isRunning = true;
    private JTextArea textArea;
    private DefaultListModel<String> modle;

    public boolean isRunning() {
        return isRunning;
    }

    public void setRunning(boolean isRunning) {
        this.isRunning = isRunning;
    }

    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    MyServer frame = new MyServer();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public MyServer() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 861, 742);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton button = new JButton("\u542F\u52A8\u670D\u52A1");
        button.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("启动服务,等待客户端链接");

                Runnable run=new Runnable() {

                    @Override
                    public void run() {
                        try {
                            ServerSocket server = new ServerSocket(8080);
                            sockets=new HashMap<>();
                            while (true) {
                                Socket socket = server.accept();// 等待客户端链接
                                System.out.println("客戶端链接进来"+socket.getInetAddress().getHostAddress());
                                String ip=socket.getInetAddress().getHostAddress();
                                sockets.put(ip, socket);
                                MyServerRead msr=new MyServerRead(socket,MyServer.this);
                                Thread thread=new Thread(msr);
                                thread.start();
                            }
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                };
                Thread t=new Thread(run);
                t.start();

            }
        });
        button.setBounds(22, 10, 475, 87);
        contentPane.add(button);

        textArea = new JTextArea();
        textArea.setBounds(100, 476, 518, 138);
        contentPane.add(textArea);

        JButton button_1 = new JButton("发送给客户");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                modle.addElement(textArea.getText());
            }
        });
        button_1.setBounds(671, 531, 93, 23);
        contentPane.add(button_1);
        modle = new DefaultListModel<>();
        JList list = new JList();
        list.setModel(modle);
        list.setBounds(100, 107, 518, 363);
        contentPane.add(list);
    }
    /**
     * 这个方法的目的是将信息放到界面上
     */
    public void readLine(String line){
        JSONObject obj=JSONObject.fromObject(line);
        String type=obj.getString("type");
        if(type.equals("toSingle")){
            String msg=obj.getString("message");
            String to=obj.getString("to");
            String from=obj.getString("from");
            String time=obj.getString("time");
            Socket toSocket=sockets.get(to);
            try {
                OutputStream os=toSocket.getOutputStream();
                BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
                bw.write(msg+"\n");
                bw.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
        modle.addElement(line);
    }

    /**
     * 这里是服务器发送的信息
     */
    public void write(String msg) {
        try {
            //sockets中存放所有的链接
            Set<String> keys = sockets.keySet();//得到HashMap中的所有key
            Iterator<String> it = keys.iterator();//keys的迭代器
            while (it.hasNext()) {
                Socket socket = sockets.get(it.next());
                OutputStream os = socket.getOutputStream();
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                System.out.println("服务器发送信息");
                bw.write(msg + "\n");
                bw.flush();
            }
            textArea.setText("");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

(二)

客户端

public class MyClient implements Runnable{
    private StartClient client;

    public MyClient(StartClient client) {
        this.client=client;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        while (true) {
            client.rend();
        }

    }

客户端界面

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import net.sf.json.JSONObject;

import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Calendar;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
import javax.swing.JLabel;

public class StartClient extends JFrame{
    private StartClient startclient;
    private JPanel contentPane;
    static boolean isRend=false;
    private JTextArea textArea;
    private JTextArea textArea_1;
    private Socket socket;
    private JTextArea textArea_2;
    private JTextArea textArea_3;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    StartClient frame = new StartClient();
                    frame.setTitle("客户端");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public StartClient() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton button = new JButton("\u8FDE\u63A5\u670D\u52A1\u5668");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                try {
                    System.out.println("开始连接服务器---");
                    socket=new Socket("192.168.0.82", 8080);
                    System.out.println("服务器连接成功");
                    MyClient client=new MyClient(StartClient.this);
                    Thread threadClient=new Thread(client);
                    threadClient.start();
                } catch (UnknownHostException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                } catch (IOException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }               
            }
        });
        button.setBounds(331, 10, 93, 23);
        contentPane.add(button);

        JButton button_1 = new JButton("\u53D1\u9001");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                    System.out.println("开始写数据");    
//                  System.out.println(textArea_3.getText());
                    String msg=creatMessage();
                    System.out.println(msg);
                    write(msg);
            }
        });
        button_1.setBounds(331, 216, 93, 23);
        contentPane.add(button_1);

        textArea = new JTextArea();
        textArea.setBounds(10, 216, 303, 23);
        contentPane.add(textArea);

        textArea_1 = new JTextArea();
        textArea_1.setBounds(10, 10, 303, 196);
        contentPane.add(textArea_1);

        textArea_2 = new JTextArea();
        textArea_2.setBounds(331, 140, 93, 23);
        contentPane.add(textArea_2);

        textArea_3 = new JTextArea();
        textArea_3.setBounds(331, 83, 93, 23);
        contentPane.add(textArea_3);

        JLabel label = new JLabel("\u6635\u79F0");
        label.setBounds(358, 55, 54, 15);
        contentPane.add(label);

        JLabel label_1 = new JLabel("\u5BF9\u65B9\u6635\u79F0");
        label_1.setBounds(341, 116, 54, 15);
        contentPane.add(label_1);
    }
    public void rend(){
        try {       
            InputStream is=socket.getInputStream();     
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
//          String s=br.readLine();
            JSONObject respone=JSONObject.fromObject(br.readLine());
            String s=respone.getString("message");
            String nicheng=respone.getString("from");
            textArea_1.append(nicheng+"说:"+s+"\n");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    } 
    public void write(String msg){
        try {
            BufferedWriter bw;
            bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));                
            String s=textArea.getText();
            bw.write(msg+"\n");
            bw.flush();
//          System.out.println(msg);
            String me=textArea_3.getText();
            textArea_1.append(me+"说:"+s+"\n");
            textArea.setText("");
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
    public String creatMessage(){
        String msg=textArea.getText();
        JSONObject obj=new JSONObject();
        Calendar calendar=Calendar.getInstance();
        long time=calendar.getTimeInMillis();
        obj.put("type", "toSingle");
        obj.put("message", msg);
        obj.put("time", ""+time);
        obj.put("from", textArea_3.getText());
        obj.put("to", textArea_2.getText());
        System.out.println(obj.toString());
        return obj.toString();
    }
}

服务器

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;

public class MyServer implements Runnable{
    private StartServer server;
    private Socket socket;
    public MyServer(StartServer server,Socket socket) {
        this.server=server;
        this.socket=socket;
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
//      server=new StartServer();
            try {
                BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                while (true) {
                    String line = br.readLine();
                    System.out.println("收到的数据"+line);
                    server.readLine(line);
                    System.out.println(line);
//                  server.textArea_1.append("客户端说:"+line+"\n");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

//      while (true) {
//          server.rend();
//      }

    }

}
服务器界面
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;

import net.sf.json.JSON;
import net.sf.json.JSONObject;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Calendar;
import java.util.HashMap;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class StartServer extends JFrame {
    private StartServer startserver;
    private JPanel contentPane;
    static boolean isRend=false;
    public Socket socket;
    public JTextArea textArea ;
    public JTextArea textArea_1;
    private HashMap  sockets;
    private DefaultListModel<String> modle;
    private String ip;
    private String frome;
    /**
     * Launch the application.
     */
    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    StartServer frame = new StartServer();
                    frame.setTitle("服务器");
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public StartServer() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);

        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);

        JButton btnNewButton = new JButton("启动服务");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("启动服务");
                Thread t=new Thread(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        try {
                            ServerSocket serversocket=new ServerSocket(8080);
                            sockets=new HashMap<>();
                            while (true) {
                                socket=serversocket.accept();
                                ip=socket.getInetAddress().getHostAddress();
                                System.out.println(ip);
//                              sockets.put(ip, socket);



                                System.out.println("客户端已连接进来"); 
                                MyServer server=new MyServer(StartServer.this,socket);
                                Thread threadServe=new Thread(server);
                                System.out.println("准备接收数据");
                                threadServe.start();
                                BufferedReader br=new BufferedReader(new InputStreamReader(socket.getInputStream()));
                                String s=br.readLine();
                                JSONObject obj=JSONObject.fromObject(s);
                                frome=obj.getString("from");
                                sockets.put(frome, socket);

                            }                           
                        } catch (IOException e1) {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }
                    }
                });
                t.start();  


            }
        });
        btnNewButton.setBounds(353, 10, 81, 23);
        contentPane.add(btnNewButton);
        textArea = new JTextArea();
        textArea.setBounds(20, 229, 329, 23);
        contentPane.add(textArea);

        JButton btnNewButton_1 = new JButton("发送");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.out.println("开始发送数据");
//              String msg=creatMessage();              
//              write();
            }
        });
        btnNewButton_1.setBounds(359, 229, 75, 23);
        contentPane.add(btnNewButton_1);

        textArea_1 = new JTextArea();
        textArea_1.setBounds(20, 10, 329, 209);
        contentPane.add(textArea_1);
    }
    public void readLine(String line){
        System.out.println("接收到数据:   "+line);
        JSONObject obj=JSONObject.fromObject(line);
        String type=obj.getString("type");
        if(type.equals("toSingle")){
            System.out.println("开始转发");
            String msg=obj.getString("message");
            String to=obj.getString("to");
            String from=obj.getString("from");
            String time=obj.getString("time");
//          Socket toSocket=(Socket) sockets.get(ip);
            frome=to;
            Socket toSocket=(Socket) sockets.get(frome);

            System.out.println(sockets.get(ip) instanceof Socket);
            try {
                OutputStream os=toSocket.getOutputStream();
                BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
                bw.write(obj.toString()+"\n");
                bw.flush();
                textArea_1.append(from+":"+msg+"\n");
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

//      modle.addElement(line);
    }
    public void rend(){
        try {
            InputStream is=socket.getInputStream();     
            BufferedReader br = new BufferedReader(new InputStreamReader(is));  
            String s=br.readLine();
            System.out.println("开始通话");
            textArea_1.append("客户端说:"+s+"\n");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    } 
    public void write(){
        BufferedWriter bw;
        try {
            bw=new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String s=textArea.getText();
            bw.write(s+"\n");
            bw.flush();
            textArea_1.append("服务器说:"+s+"\n");
            textArea.setText("");
        } catch (IOException e1) { 
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值