| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 2622 人关注过本帖
标题:Java socket怎样实现一个服务端连接多个客户端
只看楼主 加入收藏
pcx19991102
Rank: 1
等 级:新手上路
帖 子:1
专家分:0
注 册:2018-11-13
结帖率:0
收藏
已结贴  问题点数:15 回复次数:2 
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
幻紫灵心
Rank: 11Rank: 11Rank: 11Rank: 11
来 自:山咔咔里面
等 级:贵宾
威 望:53
帖 子:396
专家分:2640
注 册:2018-3-30
收藏
得分:8 
服务端用多线程,每收到一个连接就启用一个线程

saber,别哭.
2018-11-13 18:04
wlrjgzs
Rank: 16Rank: 16Rank: 16Rank: 16
等 级:版主
威 望:26
帖 子:212
专家分:1566
注 册:2017-4-10
收藏
得分:8 
楼上正解,另外说明一下,服务端不能主动的连接客户端,只能被动地等待客户端的连接。
2018-11-14 08:04
快速回复:Java socket怎样实现一个服务端连接多个客户端
数据加载中...
 
   



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

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