标题:Java socket怎样实现一个服务端连接多个客户端
取消只看楼主
pcx19991102
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2018-11-13
结帖率:0
已结贴  问题点数:15 回复次数:0 
Java socket怎样实现一个服务端连接多个客户端
----------------------------------------------服务端
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import *;
import
import
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class Server extends JFrame implements ActionListener, Runnable {
    JTextArea jTextReceive = new JTextArea();
    JTextField jTextSend = new JTextField();
    JButton jbs = new JButton("发送");
    ServerSocket server = null;
    JScrollPane jsp = new JScrollPane(jTextReceive);
    Socket clientSocket;     //负责当前线程中C/S通信中的Socket对象
    boolean flag = true;       //标记是否结束
    Thread connenThread;     //向客户端发送信息的线程
    BufferedReader sin;      //输入流对象
    DataInputStream sin1;
    DataOutputStream sout;   //输出流对象
    boolean flags = false;

    public static void main(String[] args) {
        Server MS = new Server();
        MS.serverStart();
    }
    public synchronized void changeFlag(boolean t){
       flags=t;
    }
            

    public void serverStart() {
        try {
            server = new ServerSocket(8080);    //建立监听服务
            this.setTitle("服务器端,端口号:" + server.getLocalPort());
            this.setLayout(null);
            this.setBounds(20, 00, 300, 300);
            jsp.setBounds(20, 20, 220, 100);
            jTextSend.setBounds(20, 120, 220, 50);
            jbs.setBounds(20, 170, 220, 30);
            this.add(jsp);
            this.add(jTextSend);
            this.add(jbs);
            this.setVisible(true);
            jbs.addActionListener(this);
            while (flag) {
                clientSocket = server.accept();
                jTextReceive.setText("连接已经建立完毕!\n");
                try (InputStream is = clientSocket.getInputStream()) {
                    sin = new BufferedReader(new InputStreamReader(is));
                    try (OutputStream os = clientSocket.getOutputStream()) {
                        sin1 = new DataInputStream(clientSocket.getInputStream());
                        sout = new DataOutputStream(os);
                        connenThread = new Thread(this);
                        connenThread.start();     //启动线程,向客户端发送信息
                        String aLine;
                        while(true){
                            aLine=sin1.readUTF();
                            jTextReceive.append("客户端发来信息:" +aLine+"\n");
                            if (aLine.equals("bye")) {
                                flag = false;
                                connenThread.interrupt();
                                break;
                            }
                        }
                        sout.close();
                    }
                    sin.close();
                }
                clientSocket.close();     //关闭Socket连接
                System.exit(0);          //程序运行结束
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    @Override
    public void run() {
        while (true) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
                Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                    if (flags == true) {
                    changeFlag(false);
                    String str = jTextSend.getText().trim();
                   if(str==null||str.length()<=0){}
                    else{
                    sout.writeUTF(str);
                    sout.flush();
                    jTextReceive.append("服务器发送消息:"+str+"\n");   }            
                    jTextSend.setText("");
                    }

            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

    @Override
    public void finalize()
    {
        try {
            server.close();
        } //停止ServerSocket服务
        catch (IOException e) {
            System.out.println(e);
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jbt = (JButton) e.getSource();
        if (jbt == jbs) //若单击确认对话框中的“发送”按钮
        {
            changeFlag(true);
        }
    }
}
-------------------------------------------------------------客户端
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import *;
import
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

public class MyClient extends JFrame implements ActionListener, Runnable {

    Socket clientSocket;
    JTextArea jTextReceive = new JTextArea();
    JTextField jTextSend = new JTextField();
    JButton jbc = new JButton("发送");
    JScrollPane jsp = new JScrollPane(jTextReceive);
    boolean flag = true;                   //标记是否结束
    Thread connenThread;                 //用于向服务器端发送信息
    DataInputStream cin1;
    DataOutputStream cout;
    static boolean flagclient = false;

    public static void main(String[] args) {
        new MyClient().clientStart();
    }

    public synchronized void changeFlag(boolean t) {
        flagclient = t;
    }

    public void clientStart() {
        try {                              //连接服务器端,这里使用本机
            this.setTitle("客户端,端口号:8080");
            this.setLayout(null);
            this.setBounds(20, 00, 300, 300);
            jsp.setBounds(20, 20, 220, 100);
            jTextSend.setBounds(20, 120, 220, 50);
            jbc.setBounds(20, 170, 220, 30);
            this.add(jsp);
            this.add(jTextSend);
            this.add(jbc);
            this.setVisible(true);
            jbc.addActionListener(this);
            clientSocket = new Socket("localhost", 8080);
            jTextReceive.setText("连接已经建立完毕!\n");
            while (flag) {
                try (InputStream is = clientSocket.getInputStream()) {
                    cin1 = new DataInputStream(clientSocket.getInputStream());
                    try (OutputStream os = clientSocket.getOutputStream()) {
                        cout = new DataOutputStream(os);
                        connenThread = new Thread(this);
                        connenThread.start();     //启动线程,向服务器端发送信息
                        String aLine;
                        while (true) {
                            aLine = cin1.readUTF();
                            jTextReceive.append("服务器发来信息:" + aLine + "\n");
                            if (aLine.equals("bye")) {
                                flag = false;
                                connenThread.interrupt();
                                break;
                            }
                        }
                        cout.close();
                    }
                    cin1.close();
                }
                clientSocket.close();    //关闭Socket连接
                System.exit(0);
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }

    @Override
    public void run() {

        while (true) {
            try {
                Thread.sleep(10);
            } catch (InterruptedException ex) {
                Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                if (flagclient == true) {

                    String str = jTextSend.getText().trim();
                    if(str==null||str.length()<=0){}
                    else{
                    jTextReceive.append("发送消息:" + str + "\n");
                    cout.writeUTF(str);
                    cout.flush();}
                    jTextSend.setText(null);
                    changeFlag(false);
                }

            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        JButton jbt = (JButton) e.getSource();
        if (jbt == jbc) //若单击确认对话框中的“发送”按钮
        {
            changeFlag(true);
        }
    }
}
搜索更多相关主题的帖子: Java import public new this 
2018-11-13 16:22



参与讨论请移步原网站贴子:https://bbs.bccn.net/thread-491222-1-1.html




关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.170293 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved