Java局域网对话系统
Mr.小明同学 人气:0先说一下
写的确实比较一般,别喷
为什么呢,疫情原因,学校提前两周期末考试,时间也不太充足,将就一下
服务器代码:
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<String,String> 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<String,String> 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<String,String> message= new HashMap<String, String>(); 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<String, String> 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<String,String> synuser= new HashMap<String, String>(); synuser.put("messageclass", "addUser");// 普通 消息 synuser.put( "userName",username ); synMessage(synuser); // 同步所以已在线用户, 有新用户 登录 // 其实 我们还需要 回复 该用户, 现在有哪些在线 以便于 后来登录的人 用户列表 无法更新 synUserList(message,id); continue; }else if ( mess.get("messageclass").toString().equals("userClose") ){ Map<String,String> synuser= new HashMap<String, String>(); 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<String, String> 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<UserList.length;i++) { jComboBoxOnlineUser.addItem(UserList[i]); } } } } } } catch (IOException e) { e.printStackTrace(); } } public static Map<String,String> mapStringToMap(String str){ str=str.substring(1, str.length()-1); System.out.println("ishere dk->" + str); String[] strs=str.split(","); Map<String,String> map = new HashMap<String, String>(); 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<String,String> message= new HashMap<String, String>(); 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<String,String> message= new HashMap<String, String>(); 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<String,String> message= new HashMap<String, String>(); 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地址 我写的是我自己的 想改的可以自己改
加载全部内容