基於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<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地址 我寫的是我自己的 想改的可以自己改
以上就是基於Java實現簡易的局域網對話系統的詳細內容,更多關於Java局域網對話系統的資料請關註WalkonNet其它相關文章!