Java的客户端与服务器,客户端可以发信息,想加一个让服务器也能发信息?
package Other;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketAddress;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Server extends JFrame {
    private JPanel p1, p2, p4, p5, p6;
    private JLabel lb1, lb2, lb3, lb4;
    private Container container;
    private JTextField t1, t2;
    private static JTextArea ta;
    private JButton bt;

    public Server() {
        this.setTitle("服务器");
        container = this.getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));
        lb1 = new JLabel("服务器启动面板");
        lb2 = new JLabel("服务器主机名:");
        lb3 = new JLabel("服务器端口:");
        lb4 = new JLabel("服务器收到客户机消息面板");
        bt = new JButton("启动服务器");
        bt.addActionListener(new btActionListener());
        t1 = new JTextField(10);
        t2 = new JTextField(5);
        ta = new JTextArea(15, 40);
//      ta.addActionListener(new taActionListener());
        p1 = new JPanel();
        p2 = new JPanel();
        p4 = new JPanel();
        p5 = new JPanel();
        p6 = new JPanel();
        p1.add(lb1);
        container.add(p1);
        p2.add(lb2);
        p2.add(t1);
        p2.add(lb3);
        p2.add(t2);
        p2.add(bt);
        container.add(p2);
        p4.add(lb4);
        container.add(p4);
        p5.add(ta);
        p6.add(p5);
        container.add(p6);
        this.setSize(500, 500);
        this.setVisible(true);
        this.setResizable(false);
    }

    private ServerSocket listenSocket =null;
    private Socket toClientSocket = null;
    private BufferedReader in;
    private PrintWriter out;
    public static int clientCounts = 0;
    public class taActionListener implements ActionListener{

        @Override
        public void actionPerformed(ActionEvent e) {

        }

    }

    public class btActionListener implements ActionListener {
        public void actionPerformed(ActionEvent arg0) {
            try {
                bt.setEnabled(false);
                String hostName = t1.getText();
                int hostPort = Integer.parseInt(t2.getText());
                SocketAddress serverAddr = new InetSocketAddress(
                        InetAddress.getByName(hostName),hostPort);
                listenSocket = new ServerSocket();
                listenSocket.bind(serverAddr);
                ta.append("服务器开始等待客户机连接…\n");
            } catch (Exception e) {}

            //创建匿名线程,创建响应客户机的会话线程
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        while (true) { // 处理客户机连接

                            toClientSocket = listenSocket.accept(); // 侦听并接受客户机连接
                            clientCounts++;
                            ta.append(toClientSocket.getRemoteSocketAddress() + 
                                    "客户机编号" + clientCounts + "会话开始…\n");
                            // 创建客户线程clientThread,实现一客户一线程
                            Thread clientThread = new ClientThread(toClientSocket, clientCounts);
                            clientThread.start();
                        }//end while
                    } catch (IOException e) {
                        JOptionPane.showMessageDialog(null, e.getMessage(), 
                                "错误提示", JOptionPane.ERROR_MESSAGE);
                        return;
                    }
                }//end run()

            }).start();
        }
    }

    private void formWindowClosing (java.awt.event.WindowEvent evt){
        try {
            if(in != null)in.close();
            if(out != null)out.close();
            if (listenSocket != null)listenSocket.close();
            if (toClientSocket != null)toClientSocket.close();
        } catch (Exception e) {}
    }

    public static void main(String[] args) {
        new Server();
    }

    public static JTextArea getScreen() {
        return ta;
    }
}

服务器代码:
package Other;
import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Client extends JFrame {

    private JPanel p1, p2, p3, p5, p6, p7;
    private JLabel lb1, lb2, lb3, lb4, lb5;
    private Container container;
    private JTextField t1, t2, t3;
    private static JTextArea ta;
    private JButton bt1, bt2;
    public Client(){
        this.setTitle("客户机");
        container = this.getContentPane();
        container.setLayout(new FlowLayout(FlowLayout.LEFT));
        lb1 = new JLabel("通信面板");
        lb2 = new JLabel("服务器主机名:");
        lb3 = new JLabel("服务器端口:");
        lb4 = new JLabel("待发送消息:");
        lb5 = new JLabel("服务器Echo消息面板");
        bt1 = new JButton("连接服务器");
        bt2 = new JButton(" 发          言 ");
        bt1.addActionListener(new bt1ActionListener());
        bt2.addActionListener(new bt2ActionListener());
        t1 = new JTextField(10);
        t2 = new JTextField(5);
        t3 = new JTextField(25);
        ta = new JTextArea(15, 40);
        p1 = new JPanel();
        p2 = new JPanel();
        p3 = new JPanel();
        p5 = new JPanel();
        p6 = new JPanel();
        p7 = new JPanel();
        p1.add(lb1);
        container.add(p1);
        p2.add(lb2);
        p2.add(t1);
        p2.add(lb3);
        p2.add(t2);
        p2.add(bt1);
        container.add(p2);
        p3.add(lb4);
        p3.add(t3);
        p3.add(bt2);
        container.add(p3);
        p5.add(lb5);
        container.add(p5);
        p6.add(ta);
        p7.add(p6);
        container.add(p7);
        this.setSize(500, 500);
        this.setVisible(true);
        this.setResizable(false);           
    }

    private Socket clientSocket = null;
    private BufferedReader in;
    private PrintWriter out;
    public class bt1ActionListener implements ActionListener {
        public void actionPerformed(ActionEvent arg0) {
            try {
                bt1.setEnabled(false);
                String remoteName = t1.getText();
                int remotePort = Integer.parseInt(t2.getText());
                SocketAddress remoteAddr = new InetSocketAddress(
                        InetAddress.getByName(remoteName),remotePort);
                clientSocket = new Socket();
                clientSocket.connect(remoteAddr);
                ta.append("连接服务器成功,会话开始…\n");
                out = new PrintWriter(new OutputStreamWriter(
                        clientSocket.getOutputStream(),"UTF-8"),true);
                in = new BufferedReader(new InputStreamReader(
                        clientSocket.getInputStream(),"UTF-8"));

            } catch (Exception e) {
                JOptionPane.showConfirmDialog(null, e.getMessage(),
                        "连接错误",JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
    }

    public class bt2ActionListener implements ActionListener {
        public void actionPerformed(ActionEvent arg0) {
            if(clientSocket == null){
                JOptionPane.showMessageDialog(null, "请先检查服务器连接情况。\n确保客户及连接服务器!", 
                        "错误提示", JOptionPane.ERROR_MESSAGE);
                return;
            }

            String outStr = t3.getText();
            if(outStr.length() == 0){
                JOptionPane.showMessageDialog(null, "请输入发送消息!", 
                        "提示", JOptionPane.ERROR_MESSAGE);
                return;
            }

            out.println(outStr);
            t3.setText(""); 
            try {
                String inStr;
                inStr = in.readLine();
                ta.append("Echo:" + inStr + "\n");
            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, "客户机接收消息错误!", 
                        "错误提示", JOptionPane.ERROR_MESSAGE);
                return;
            }
        }
    }

    private void formWindowClosing(java.awt.event.WindowEvent evt){
            try {
                if(in != null)in.close();
                if(out != null)out.close();
                if(clientSocket != null)clientSocket.close();
            } catch (Exception e) {}
    }

    public static void main(String[] args) {
        new Client();
    }

}
多线程:
package Other;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

public class ClientThread extends Thread {
    private Socket toClientSocket = null;
    private BufferedReader in;
    private PrintWriter out;
    public static int clientCounts = 0;
    public ClientThread(Socket toClientSocket,int clientCounts){
        this.toClientSocket = toClientSocket;
        this.clientCounts = clientCounts;
    }
    @Override
    public void run() {
        try {
            in = new BufferedReader(
                    new InputStreamReader(toClientSocket.getInputStream(),"UTF-8"));
            out = new PrintWriter(
                new OutputStreamWriter(toClientSocket.getOutputStream(),"UTF-8"),true);
            //根据服务器协议,在网络流上进行读写操作
            String recvStr;
            while((recvStr = in.readLine()) != null){       //客户机关闭,反复等待
                System.out.println(recvStr);
                Date date = new Date();                     //和接受客户机消息
                DateFormat format = new SimpleDateFormat("yyyy-mm-dd hh:mm:ss");
                String time = format.format(date);
                //解析并显示收到的信息
                Server.getScreen().append(toClientSocket.getRemoteSocketAddress()
                        + "客户机编号:" + clientCounts + "消息:" + recvStr + ":" + time + "\n");
                //按照Echo协议原封不动会送消息
                out.println(toClientSocket.getLocalAddress() + "客户机编号:" + clientCounts + 
                        "Echo消息:" + recvStr + ":" + time);
            }//end while
            Server.clientCounts--;
            //远程客户机断开,释放资源
            if(in != null)in.close();
            if(out != null)out.close();
            if (toClientSocket != null)toClientSocket.close();
        } catch (Exception e) {}
    }//end run
}//end class
0

1个回答

0
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!