2015/8/7/C-S/通过服务器转发消息

通过服务器转发内容的例子

这里写图片描述

package com.baidu.test;

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

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

import net.sf.json.JSONObject;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JList;
import java.awt.event.ActionListener;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class Server extends JFrame {

    private JPanel contentPane;
    private DefaultListModel<String> model;
    private JList list;
    private HashMap<String, Socket> sockets;
    private Socket socket;
    private JTextArea textArea_1;
    private JTextArea textArea;

    /**
     * 这个方法主要是接收客户端发送过来的json字符串并将字符串解析
     * 通过传送过来的信息来判断是发送给个人的还是发送给所有人的
     * 并将解析出来的内容发送给指定的端口
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Server frame = new Server();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Server() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 279, 483);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        /**
         * 启动服务器,创建一个新的线程,用来等待客户端的链接,并将已经链接的客户端端口和Ip地址放入到HashMap中
         * 然后为每一个客户端创建一个新的线程用于读取从客户端输入的内容
         * @param line
         */
        JButton button = new JButton("启动服务");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("服务器启动");
                Runnable run=new Runnable() {
                    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);
                                Thread thread=new Thread(new ServerRead(Server.this, socket));
                                thread.start();
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                };
                Thread thread=new Thread(run);
                thread.start();
            }
        });
        button.setBounds(160, 379, 93, 23);
        contentPane.add(button);

        JButton button_1 = new JButton("发送");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
//              write();
                textArea.setText("");
            }
        });
        button_1.setBounds(160, 412, 93, 23);
        contentPane.add(button_1);
        /**
         * 关闭程序
         */
        JButton button_2 = new JButton("关闭");
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        button_2.setBounds(160, 317, 93, 23);
        contentPane.add(button_2);
        /**
         * 创建列表并在列表上添加滚动条
         */
        list= new JList();
        model=new DefaultListModel<>();
        list.setModel(model);
        list.setBounds(20, 10, 233, 298);

        JScrollPane scrollPane = new JScrollPane(list);
        scrollPane.setBounds(20, 10, 233, 298);
        contentPane.add(scrollPane);
//      contentPane.add(list);

        textArea = new JTextArea();
        textArea.setBounds(10, 317, 140, 118);
        contentPane.add(textArea);

        textArea_1 = new JTextArea();
        textArea_1.setBounds(160, 350, 93, 23);
        contentPane.add(textArea_1);
    }
    /**
     * 解析JSON格式的内容并判断发送的类型是给个人的还是给全部人的
     * 从JSON格式中得到要转发到的端口将需要转发的内容发送个该端口
     */
    public void read(String line){
        JSONObject obj=JSONObject.fromObject(line);
        String type=obj.getString("type");
        if (type.equals("toSingle")) {
            String msg=obj.getString("message");
            String time=obj.getString("time");
            String from=obj.getString("from");
            String to=obj.getString("to");
            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();
            }

        }
        model.addElement(line);
    }


//          Socket socket1 =Socket(textArea_1.getText());
//  public void write(){
//      try {
//          for (Socket socket : sockets) {
//              OutputStream os=socket.getOutputStream();
//              BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
//              String words=textArea.getText();
//              model.addElement("服务器发送给客户端:"+words);
//              bw.write(words+"\n");
//              bw.flush();
//          }
//      } catch (UnknownHostException e1) {
//          e1.printStackTrace();
//      } catch (IOException e1) {
//          e1.printStackTrace();
//      }
//      
//  }
}

package com.baidu.test;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.Point;

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

import net.sf.json.JSONObject;

import javax.swing.DefaultListModel;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.JList;
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 java.awt.event.ActionEvent;
import javax.swing.JTextArea;

public class Client extends JFrame {

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

    /**
     * 这个方法的主要目的是发送给服务器封装好的json字符串方便用服务器转发给目的客户端
     * Launch the application.
     */
    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    Client frame = new Client();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * Create the frame.
     */
    public Client() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 313, 450);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        setContentPane(contentPane);
        contentPane.setLayout(null);
        /**
         * 生成json格式字符串 
         * 发送给服务器
         * 清空文本
         */
        JButton button = new JButton("发送");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                String msg=creatMessage();
                write(msg);
                textArea.setText("");
            }
        });
        button.setBounds(194, 379, 93, 23);
        contentPane.add(button);
        /**
         * 关闭程序
         */
        JButton button_1 = new JButton("关闭");
        button_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        button_1.setBounds(194, 332, 93, 23);
        contentPane.add(button_1);
        /**
         * 启动客户端。在将客户端连接到指定端口
         * 启用监听线程,用于接收来自服务器的消息
         */
        JButton button_2 = new JButton("链接");
        button_2.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent arg0) {
                try {
                    System.out.println("客户端连接");
                    socket=new Socket("192.168.0.113", 8080);
                    Thread thread=new Thread(new ClientRead(Client.this));
                    thread.start();
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
        button_2.setBounds(194, 287, 93, 23);
        contentPane.add(button_2);
        /**
         * 创建列表,并在列表上加上滚动条
         */
        list= new JList();
        model=new DefaultListModel<>();
        list.setModel(model);

        JScrollPane jscrol = new JScrollPane(list);
        jscrol.setBounds(10, 10, 277, 268);
        contentPane.add(jscrol);

        list.setBounds(10, 10, 277, 268);
//      contentPane.add(list);
        /**
         * 文本输入
         */
        textArea = new JTextArea();
        textArea.setBounds(20, 287, 168, 115);
        contentPane.add(textArea);
    }
    /**
     * 
     * @return 返回Json String格式的信息,发送给所有人
     */
    public String creatMessage(){
        JSONObject obj=new JSONObject();
        String msg=textArea.getText();
        Calendar calendar=Calendar.getInstance();
        String ip=socket.getLocalAddress().getHostAddress();
        long time=calendar.getTimeInMillis();
        obj.put("type", "toSingle");
        obj.put("message", msg);
        obj.put("time", time);
        obj.put("from", ip);
        obj.put("to", "192.168.0.113");
        return obj.toString();
    }
    /**
     * 将此信息发送服务器
     * @param words即将发送的信息
     */
    public void write(String msg){
        try {
            OutputStream os=socket.getOutputStream();
            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(os));
            System.out.println("向服务器发送:"+msg);
            bw.write(msg+"\n");
            model.addElement("客户端说:"+textArea.getText());
            bw.flush();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    /**
     * 读取服务器的内容,并将内容添加到客户端的列表上
     */
    public void read(){
        try {
            InputStream is=socket.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            String line=br.readLine();
            model.addElement("服务器说:"+line);
            System.out.println("服务器说:"+line);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
package com.baidu.test;

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

public class ServerRead implements Runnable{
    private Socket socket;
    private Server server;
    public ServerRead(Server server,Socket socket) {
        this.server=server;
        this.socket=socket;
    }
    /**
     * 用于读取客户端的内容
     */
    @Override
    public void run() {
        try {
            InputStream is = socket.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(is));
            while(true){
            String line=br.readLine();
            System.out.println("客户端说:"+line);
            server.read(line);
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}
package com.baidu.test;

public class ClientRead implements Runnable{
    private Client client;
     public ClientRead(Client client) {
         this.client=client;
    }
     /**
      * 用于读取服务器的内容
      */
    @Override
    public void run() {
        while(true){
        client.read();
        }
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值