千家信息网

基于Java怎么实现简易的局域网对话系统

发表于:2025-01-21 作者:千家信息网编辑
千家信息网最后更新 2025年01月21日,基于Java怎么实现简易的局域网对话系统,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。先说一下写的确实比较一般,别喷为什么呢,疫情原因,
千家信息网最后更新 2025年01月21日基于Java怎么实现简易的局域网对话系统

基于Java怎么实现简易的局域网对话系统,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

先说一下

写的确实比较一般,别喷

为什么呢,疫情原因,学校提前两周期末考试,时间也不太充足,将就一下

服务器代码:

package xcvcvcx;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.nio.charset.StandardCharsets;import java.util.HashMap;import java.util.Map;public class Server {  static int index = 0;  static BufferedWriter[] userWrite = new BufferedWriter[100];  static BufferedReader[] userRead = new BufferedReader[100];  static Socket[] userSocket = new Socket[100];  static String[] userId = new String[100];  static String[] userName = new String[100];  public static void main(String[] args) throws IOException {    ServerSocket ss = new ServerSocket(6666); // 监听指定端口    System.out.println("server is running...");    index = 0;    for (;;) {      Socket sock = ss.accept();      String idd = sock.getRemoteSocketAddress().toString();      System.out.println("connected from " + sock.getRemoteSocketAddress());      userSocket[index] = sock;      Thread t = new Handler(sock);      ((Handler) t).userId = idd;      userId[index]=((Handler) t).userId =idd;      t.start();    }  }}class Handler extends Thread {  Socket sock;  BufferedWriter writer;  BufferedReader reader;  String username;  String userId;  public Handler(Socket sock) {    this.sock = sock;  }  public void synMessage(Map message) throws IOException {    BufferedWriter writer;    BufferedWriter[] user =Server.userWrite;    int isall =1;    String dis = "a";    if ( message.get("messageclass").toString().equals("normally")  ){      dis = message.get("distination");      System.out.println(dis);      System.out.println();      if (dis.equals("all") == false){        System.out.println("no isall");        isall= 0;      }    }    int len = Server.index;    for(int i =0; i< len;i++)    {      if (Server.userWrite[i] == null){        continue;      }      System.out.println("vf");      if (isall == 0){        // 专门的消息        if (Server.userName[i].equals(dis)){          message.put( "distinationId",Server.userId[i] );          writer = user[i];          writer.write(message.toString() + "\n");          System.out.print("专门消息发送成功");          writer.flush();          return;        }        continue;      }      message.put( "distinationId",Server.userId[i] );      if (Server.userWrite[i] == null){        continue;      }      if ( Server.userId[i].equals(this.userId) == false)      {        writer = user[i];        writer.write(message.toString() + "\n");        System.out.print("进来了");        writer.flush();      }else {        writer = user[i];        writer.write(message.toString() + "\n");        System.out.print("进来了");        writer.flush();      }    }  }  public  void synUserList(Map message,String Id){    BufferedWriter writer;    BufferedWriter[] user =Server.userWrite;    // 封装 用户列表    // 规定用户名不可以有空格    int len = Server.index;    String userLis = "here";    for (int i = 0; i< len ; i++)    {      System.out.println(userLis);      if (Server.userWrite[i]!=null){        if (message.get("userId").equals(Server.userId[i])){          continue;        }else {          if (Server.userName[i] ==null){            continue;          }          userLis = userLis + " " + Server.userName[i];        }      }    }    message.put( "distinationId",Id);    message.put( "userList",userLis);    message.put("messageclass","synUserList");    for(int i =0; i< len;i++)    {      if (Server.userWrite[i] == null){        continue;      }      if ( Server.userId[i].equals(Id))      {        writer = user[i];        try {          writer.write(message.toString() + "\n");          writer.flush();          return;        } catch (IOException e) {          e.printStackTrace();        }      }    }  }  @Override  public void run() {    try (InputStream input = this.sock.getInputStream()) {      try (OutputStream output = this.sock.getOutputStream()) {        handle(input, output);      }    } catch (Exception e) {      try {        this.sock.close();      } catch (IOException ioe) {      }      System.out.println("client disconnected.");    }  }  private void handle(InputStream input, OutputStream output) throws IOException {    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));    BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));    this.writer = writer;    this.reader = reader;    int inde = Server.index;    Server.index++;    Server.userRead[inde] = reader;    Server.userWrite[inde] = writer;    Map message=  new HashMap();    message.put("messageclass", "synId");// 普通 消息    message.put( "userId",userId );    message.put( "userIndex",String.valueOf(inde) );    String  to=message.toString();    writer.write(to+'\n');    writer.flush();    for (;;) {      String s = reader.readLine();      if (s == null){        continue;      }//      System.out.print(s);//      synMessages(s);      Map mess= Client.mapStringToMap(s);////      System.out.print(s);      if(mess.get("messageclass").toString().equals("normally"))      {        System.out.print("irieowmxn");        synMessage(mess);        continue;      }else  if (mess.get("messageclass").toString().equals("synUserName")){        System.out.println("now synuser");        String id = mess.get("userId");        System.out.println(mess.toString());        username = mess.get("user");        int index = Integer.parseInt( mess.get("userIndex") );        Server.userName[index] = username;        // 同步 在线用户        Map synuser=  new HashMap();        synuser.put("messageclass", "addUser");// 普通 消息        synuser.put( "userName",username );        synMessage(synuser);        // 同步所以已在线用户, 有新用户 登录        // 其实  我们还需要   回复 该用户,  现在有哪些在线    以便于  后来登录的人   用户列表  无法更新        synUserList(message,id);        continue;      }else if ( mess.get("messageclass").toString().equals("userClose") ){        Map synuser=  new HashMap();        synuser.put("messageclass", "userClose");// 普通 消息        synuser.put( "userName",username );        synMessage(synuser);        int iin = Integer.parseInt(mess.get("userIndex"));        Server.userWrite[iin] = null;      }      if (s.equals("bye")) {        writer.write("bye\n");        writer.flush();        break;      }    }  }}

客户端:

package xcvcvcx;import java.awt.BorderLayout;import java.awt.FlowLayout;import java.awt.GridLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.ItemEvent;import java.awt.event.ItemListener;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.SocketAddress;import java.nio.charset.StandardCharsets;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;import java.util.Scanner;import javax.swing.JButton;import javax.swing.JComboBox;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JPanel;import javax.swing.JScrollPane;import javax.swing.JTextArea;import javax.swing.JTextField;import javax.swing.WindowConstants;public class Client extends JFrame implements ActionListener ,ItemListener {  private String currentt_userName = null;  //各种组件  JLabel jLabelSeverIP,jLabelSeverPort,jLabelReceiveData,jLabelSentData;  JTextField jTextFieldSeverIP,jTextFieldSeverPort,jTextFieldSentData;  JButton jButtonSetupSever,jButtonCloseNetwork,jButtonSent;  JTextArea jTextAreaReceiveData;  JButton jButtonExit;  // 当前在线用户部分  JLabel jLabelOnlinUser;  JComboBox jComboBoxOnlineUser;  //组件完毕  BufferedReader reader;  BufferedWriter writer;  // 存储用户信息  JLabel jLabelusername;  JTextField jTextFieldusername;  String userId ;  Socket sock;  int userIndex;  // 服务连接相关  String ServerAddress ="192.168.43.240" ; // 可以自己设置  int port = 6666;  public Client(){    init();  }  public void init(){    //初始化    jLabelReceiveData=new JLabel("接受数据:");    jLabelSentData=new JLabel("发送数据:");    jLabelSeverIP=new JLabel("服务器IP");    jLabelSeverPort=new JLabel("服务器端口");    jTextFieldSentData=new JTextField(15);    jTextFieldSeverIP=new JTextField(7);    jTextFieldSeverPort=new JTextField(7);    jButtonCloseNetwork=new JButton("关闭服务");    jButtonSent=new JButton("发送");    jButtonSetupSever=new JButton("开启服务");    jTextAreaReceiveData=new JTextArea(20,15);    JScrollPane scroller = new JScrollPane(jTextAreaReceiveData);    scroller.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);    jTextAreaReceiveData.setWrapStyleWord(true);//设置单词在一行不足容纳时换行    jTextAreaReceiveData.setLineWrap(true);//设置文本编辑区自动换行默认为true,即会"自动换行"    //this.add(editArea,BorderLayout.CENTER);//向窗口添加文本编辑区    jButtonExit = new JButton("退出");    //组件初始化    // 存储  用户信息    jLabelusername = new JLabel("用户名");    jTextFieldusername = new JTextField(10);    jLabelOnlinUser = new JLabel("在线用户");    jComboBoxOnlineUser = new JComboBox();    jComboBoxOnlineUser.addItemListener(this::itemStateChanged);    jComboBoxOnlineUser.addItem("self");    JPanel panel1=new JPanel();    panel1.setLayout(new FlowLayout());    panel1.add(jLabelSeverIP);    panel1.add(jTextFieldSeverIP);    panel1.add(jLabelSeverPort);    panel1.add(jTextFieldSeverPort);    panel1.add(jButtonSetupSever);    panel1.add(jButtonCloseNetwork);    JPanel panel2=new JPanel();    panel2.add(jLabelReceiveData);    JPanel jPaneluserinfor = new JPanel();    jPaneluserinfor.setLayout(new FlowLayout());    jPaneluserinfor.add(jLabelusername);    jPaneluserinfor.add((jTextFieldusername));    jPaneluserinfor.add(jLabelOnlinUser);    jPaneluserinfor.add(jComboBoxOnlineUser);    JPanel jPanel1=new JPanel();    jPanel1.setLayout(new GridLayout(3,1));    jPanel1.add(panel1);    jPanel1.add(jPaneluserinfor);    jPanel1.add(panel2);    JPanel panel3=new JPanel();    panel3.setLayout(new FlowLayout());    panel3.add(jLabelSentData);    JPanel panel4=new JPanel();    panel4.setLayout(new FlowLayout());    panel4.add(jTextFieldSentData);    panel4.add(jButtonSent);    panel4.add(jButtonExit);    JPanel jPanel2=new JPanel();    jPanel2.setLayout(new GridLayout(2,1));    jPanel2.add(panel3);    jPanel2.add(panel4);    JPanel jPanel=new JPanel();    jPanel.setLayout(new BorderLayout());    jPanel.add(jPanel1,BorderLayout.NORTH);    jPanel.add(scroller,BorderLayout.CENTER);    jPanel.add(jPanel2,BorderLayout.SOUTH);    //完成组件组合    jButtonSent.addActionListener(this);    jButtonSetupSever.addActionListener(this);    jButtonCloseNetwork.addActionListener(this);    jButtonExit.addActionListener(this);    setSize(600,400);    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);    add(jPanel);    setVisible(true);    //显示    jButtonCloseNetwork.setEnabled(false);    jTextFieldSeverIP.setText(ServerAddress);    jTextFieldSeverPort.setText(String.valueOf(port));    jTextAreaReceiveData.append("本程序只用于简单演示,\n若要修改服务器地址或端口,请修改指定代码,暂不支持手动指定\n\n\n");    // 连接服务器    try {      Socket sock = new Socket(ServerAddress, port);      this.sock = sock;      try (InputStream input = sock.getInputStream()) {        try (OutputStream output = sock.getOutputStream()) {          BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));          BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));          SocketAddress id =  sock.getRemoteSocketAddress();          userId = sock.getRemoteSocketAddress().toString();          this.writer =writer;          this.reader = reader;          while(true)            for (; ; ) {              String resp = reader.readLine();              while (resp == null) {                resp = reader.readLine();              }              System.out.println("<<< " + resp);              Map message = mapStringToMap(resp);              if (message.get("messageclass").equals("synId")) {                System.out.println(userId);                userId = message.get("userId");                System.out.println(message.keySet());                System.out.println(userId);                // 更新 服务器 接口 处的  内容                jTextAreaReceiveData.append("已为您成功分配id  请填写用户名,并开启服务");                jTextAreaReceiveData.append(resp);                jTextAreaReceiveData.append("\n");                userIndex = Integer.parseInt(message.get("userIndex"));                continue;              } else if (message.get("messageclass").equals("normally")) {                resp = message.toString();                System.out.print("748328");                // 正常消息                String showMess = "";                String dist = message.get("distination");                if (dist.equals("all")){                  showMess = showMess.concat("消息类型:全体消息" + '\n');                }else {                  showMess = showMess.concat("消息类型:私发消息" + '\n');                }                showMess = showMess.concat("消息时间: " + message.get("time") +  '\n');                showMess = showMess.concat("消息内容: " + message.get("content") +  '\n');                showMess = showMess.concat("消息来源: " + message.get("user") +  '\n');                jTextAreaReceiveData.append(showMess);                jTextAreaReceiveData.append("\n\n");              } else if (message.get("messageclass").equals("addUser")) {                if (currentt_userName ==null){                  continue;                }                System.out.println(message.toString());                String newname = message.get("userName");                if (newname.equals(currentt_userName) == false) {                  jComboBoxOnlineUser.addItem(newname);                  jTextAreaReceiveData.append("有新用户上线了:他是: " + newname + "\n\n" );                }              } else if (message.get("messageclass").toString().equals("userClose")) {                String name = message.get("userName");                System.out.println("现在 删除 user: " + name);                jTextAreaReceiveData.append("有用户下线了:他是: " + name + "\n\n" );                jComboBoxOnlineUser.removeItem(name);              }else if( message.get("messageclass").toString().equals("synUserList") ){                String Lis = message.get("userList");                String[] UserList = Lis.split(" ");                int i;                for(i=1; i mapStringToMap(String str){    str=str.substring(1, str.length()-1);    System.out.println("ishere dk->" + str);    String[] strs=str.split(",");    Map map = new HashMap();    for (String string : strs) {      String key=string.split("=")[0];      String value=string.split("=")[1];      value = value.trim();      key = key.trim();      map.put(key, value);    }    return map;  }  public static void main(String[] args) throws IOException {     Client a = new Client();  }  private static void handle(InputStream input, OutputStream output) throws IOException {    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(output, StandardCharsets.UTF_8));    BufferedReader reader = new BufferedReader(new InputStreamReader(input, StandardCharsets.UTF_8));    Scanner scanner = new Scanner(System.in);    System.out.println("[server] " + reader.readLine());    for (;;) {      System.out.print(">>> "); // 打印提示      String s = scanner.nextLine(); // 读取一行输入      writer.write(s);      writer.newLine();      writer.flush();      String resp = reader.readLine();      System.out.println("<<< " + resp);      if (resp.equals("bye")) {        break;      }    }  }  void update() throws IOException {    for (;;) {      System.out.print("lkdfvmndfjk");      String resp = reader.readLine();      System.out.println("<<< " + resp);      jTextAreaReceiveData.append(resp);      if (resp.equals("bye")) {        break;      }    }  }  static String time (){    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式    return df.format( new Date() ).toString();  }  @Override  public void actionPerformed(ActionEvent e) {    if (e.getSource()==jButtonSent){        if (jTextFieldSentData.getText() == "") {          jTextAreaReceiveData.append("发送不可为空"+"\n");        }else {          this.currentt_userName = jTextFieldusername.getText().toString();          Map message=  new HashMap();          message.put("messageclass", "normally");// 普通 消息          message.put("user",currentt_userName);          message.put( "userId",userId );          String  to=jTextFieldSentData.getText();          message.put("content",to);          message.put("time",time());          String distina =   jComboBoxOnlineUser.getSelectedItem().toString();          if (distina.equals("self")){            // 发给所有人            System.out.println("查看");            message.put("distination","all");          }else {            // 发给某人            message.put("distination",distina);          }          String ans  = message.toString();          to = ans;          try {            writer.write(to+"\n");            writer.flush();          }catch (Exception ee){            System.out.println(ee.toString());            jTextAreaReceiveData.append("发送失败"+"\n");          }        }      }else if (e.getSource() == jButtonCloseNetwork){      try {        sock.close();      } catch (IOException e1) {        e1.printStackTrace();      }    }else if(e.getSource() == jButtonSetupSever){      String name = jTextFieldusername.getText();      if (name.equals("")){        jTextAreaReceiveData.append("用户名不可为空");        // 不可为空  提示        return;      }      currentt_userName = name;      Map message=  new HashMap();      message.put("messageclass", "synUserName");// 普通 消息      message.put("user",currentt_userName);      message.put( "userId",userId );      message.put( "userIndex",String.valueOf(userIndex) );      try {        writer.write(message.toString()+"\n");        writer.flush();        jButtonCloseNetwork.setEnabled(true);        jButtonSetupSever.setEnabled(false);      } catch (IOException e1) {        e1.printStackTrace();      }      // 同步  用户名    }else if (e.getSource()== jButtonExit){      // 关闭按钮      Map message=  new HashMap();      message.put("messageclass", "userClose");// 普通 消息      message.put("user",currentt_userName);      message.put( "userId",userId );      message.put( "userIndex",String.valueOf(userIndex) );      try {        writer.write(message.toString()+"\n");        writer.flush();        System.out.println(message.toString());      } catch (IOException e1) {        e1.printStackTrace();      }// 发送下线消息      jComboBoxOnlineUser.removeAllItems();    }  }  @Override  public void itemStateChanged(ItemEvent e) {  }}

里面的ip地址 我写的是我自己的 想改的可以自己改

看完上述内容,你们掌握基于Java怎么实现简易的局域网对话系统的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注行业资讯频道,感谢各位的阅读!

消息 用户 服务 普通 服务器 用户名 在线 内容 组件 端口 同步 局域 局域网 简易 系统 对话 成功 一行 下线 代码 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 网络安全中的安全策略模型 js连接oracle数据库 软件开发矩阵 广州软件开发app公司 网络安全行为红线是有条件 直播IM服务器登录失败 长沙大学计算网络技术好吗 网络安全是基建的基石 光荣腿甲数据库 电解车间风险数据库 鲲鹏架构有哪些品牌服务器 软件开发工具最重要的信息出口是 数据库中介兼职管理系统 品诚网络技术有限公司 肇庆市软件开发企业 北京石景山区服务器回收 软件开发小程序都包过审吗 obs推流b站和服务器断开连接 打印机扫描显示服务器地址未登记 重庆出库管理erp软件开发 滴滴云服务器是什么意思 p2p网络技术如何实现 梦幻西游三维2022新服务器 鲲鹏架构有哪些品牌服务器 数据库有哪些安全措施 学计算机网络技术需要做哪些准备 uclient软件开发 职业软件开发市场前景如何 云服务器基础运维与管理 如何用现成软件开发
0