Java programming assignments: the client sends data to the server based on the demo provided by the instructor. The server receives the data broadcast from the client.
The overall function is similar to the chat room, and the code is not too difficult, but this problem occurs during local testing:
The server saves the IP addresses of each Socket Client to the Set, and forwards the IP addresses to all the current IP addresses each time the data is received. However, during the demonstration on the local machine, all the ChatClient clients opened are the same IP address. How can this problem be tested?
The solution is to forward the server to multiple different ports during the local test, so that the running client listens on different ports (just to implement broadcast, in actual applications, IP addresses are used for forwarding ).
Client code:
Import javax. print. attribute. hashPrintServiceAttributeSet; import javax. swing. *; import java. awt. borderLayout; import java. awt. dimension; import java. awt. flowLayout; import java. awt. toolkit; import java. awt. event. *; import java. io. *; import java.net. *; import java. util. *; public class ChatClient extends JFrame {JTextArea contents = new JTextArea (); JLabel label1 = new JLabel ("server address"); JTextField address = n Ew JTextField (); JLabel label2 = new JLabel ("username"); JTextField username = new JTextField (); JButton online = new JButton ("online "); JButton offline = new JButton ("deprecate"); JTextField input = new JTextField (); JButton send = new JButton ("send"); boolean onlineFlag = false; public ChatClient () {super ("Chat Client"); contents. setEditable (false); getContentPane (). add (contents); JPanel p1 = new JPanel (); p1.se TLayout (new FlowLayout (FlowLayout. LEADING); address. setPreferredSize (new Dimension (100, 28); username. setPreferredSize (new Dimension (80, 28); input. setPreferredSize (new Dimension (180, 28); p1.add (label1); p1.add (address); p1.add (label2); p1.add (username); p1.add (online ); p1.add (offline); p1.add (input); p1.add (send); offline. setEnabled (false); send. setEnabled (false); getContentPane (). add (p1, Bo RderLayout. SOUTH); addWindowListener (new WindowAdapter () {public void windowClosing (custom wevent we) {onlineFlag = false; Map <String, Object> m1 = new HashMap <String, Object> (); m1.put ("time", new Date (); // launch time m1.put ("username", getUsername (); m1.put ("onlineFlag", onlineFlag ); send (getServerAddress (), 2222, m1); System. exit (0) ;}}); ActionListener al = new ActionListener () {public void act Ionreceivmed (ActionEvent AE) {String server = getServerAddress (); if (server = null | server. length () = 0) {JOptionPane. showMessageDialog (ChatClient. this, "Enter the server address! "); Return;} if (AE. getSource () = online) {// the user clicks the publish button if (! OnlineFlag) {onlineFlag = true; Map <String, Object> m1 = new HashMap <String, Object> (); m1.put ("time", new Date ()); // launch time: m1.put ("username", getUsername (); m1.put ("onlineFlag", onlineFlag); online. setEnabled (false); offline. setEnabled (true); send. setEnabled (true); address. setEnabled (false); username. setEnabled (false); send (getServerAddress (), 2222, m1) ;}} else {// if (onlineFlag ){ OnlineFlag = false; Map <String, Object> m1 = new HashMap <String, Object> (); m1.put ("time", new Date ()); // launch time: m1.put ("username", getUsername (); m1.put ("onlineFlag", onlineFlag); online. setEnabled (true); offline. setEnabled (false); send. setEnabled (false); address. setEnabled (true); username. setEnabled (true); send (getServerAddress (), 2222, m1) ;}}}; ActionListener Al = new ActionListener (){ Public void actionreceivmed (ActionEvent AE) {Map <String, Object> m1 = new HashMap <String, Object> (); m1.put ("time", new Date ()); m1.put ("username", getUsername (); m1.put ("input", getInput (); send (getServerAddress (), 2222, m1) ;}; send. addActionListener (Al2O3); online. addActionListener (al); offline. addActionListener (al); // setDefaultCloseOperation (JFrame. EXIT_ON_CLOSE); setSize (720,400); Dimen Sion d = Toolkit. getdefatooltoolkit (). getScreenSize (); setLocation (d. width-720)/2, (d. height-400)/2); setVisible (true); new Thread () {public void run () {try {// receives the chat content sent by the server on port 2221, including online and offline messages. DatagramSocket rSocket = new DatagramSocket (2220); while (true) {byte [] buffer = new byte [1024*16]; DatagramPacket recvPacket = new DatagramPacket (buffer, buffer. length); rSocket. receive (recvPacket); byte [] data = recvPacket. getData (); byte [] recvData = new byte [recvPacket. getLength ()]; System. arraycopy (buffer, 0, recvData, 0, recvData. length); // Save the data received from the server to Map and display Map <String, Object> map = convertByteArrayToMap (recvData); if (map. containsKey ("onlineFlag") {// publish or deprecate boolean B = (boolean) map. get ("onlineFlag"); if (B) {// publish map. put ("input", "online");} else {// deprecate map. put ("input", "deprecate") ;}} Date time = (Date) map. get ("time"); String s = convertDateToFormatString (time); String user = (String) map. get ("username"); user = "[" + user + "]"; contents. append (s + user + ":" + (String) map. get ("input") + "\ r \ n") ;}} catch (Exception e) {e. printStackTrace ();}}}. start ();} public String getServerAddress () {String s = address. getText (); // trim Delete extra space s = s. trim (); return s;} public String getUsername () {String s = username. getText (); s = s. trim (); if (s = null | s. length () = 0) {s = "anonymous";} return s;} public String getInput () {String s = input. getText (); s = s. trim (); if (s = null | s. length () = 0) {s = "do not want to say anything";} return s;} public static String convertDateToFormatString (Date d) {return new java. text. simpleDateFormat ("(yyyy-MM-dd HH: mm: ss )"). format (d);} public static void send (String ip, int port, Map <String, Object> map) {try {byte [] data = convertMapToByteArray (map ); datagramSocket socket = new DatagramSocket (); DatagramPacket packet = new DatagramPacket (data, data. length); packet. setSocketAddress (new InetSocketAddress (ip, port); socket. send (packet);} catch (Exception e) {e. printStackTrace () ;}} public static byte [] convertMapToByteArray (Map <String, Object> map) {try {// complete this code block, the data in the map set must be converted into ByteArrayOutputStream B = new ByteArrayOutputStream (); ObjectOutputStream ois = new ObjectOutputStream (B); ois. writeObject (map); byte [] temp = B. toByteArray (); return temp;} catch (Exception e) {e. printStackTrace ();} return null;} public static Map <String, Object> convertByteArrayToMap (byte [] data) {try {ByteArrayInputStream bais = new ByteArrayInputStream (data ); objectInputStream ois = new ObjectInputStream (bais); Map <String, Object> result = (Map <String, Object>) ois. readObject (); return result;} catch (Exception e) {e. printStackTrace ();} return null;} public static void main (String [] args) {new ChatClient ();}}
Server code:
Import java.net. datagramPacket; import java.net. datagramSocket; import java.net. inetSocketAddress; import java. util. *; import java. util. concurrent. linkedBlockingQueue; public class ChatServer {LinkedBlockingQueue <Map <String, Object> queue = new LinkedBlockingQueue <Map <String, Object> (); set <String> onlineIPs = new HashSet <String> (); // The current online IP address. Public ChatServer () {try {new Thread () {public void run () {while (true) {try {// completion program, which requires data to be retrieved from the receiving queue, traverse the online IP address set and send data to all online IP addresses if (! Queue. isEmpty () {if (! OnlineIPs. isEmpty () {for (String ip: onlineIPs) {// The following port numbers can be customized and added. The newly added ports forwarded to port 2220 can implement the broadcast ChatClient in the local machine. send (ip, 2221, queue. peek (); ChatClient. send (ip, 2220, queue. remove () ;}}// end} catch (Exception e) {e. printStackTrace ();}}}}. start (); // accept port 2222 DatagramSocket serverSocket = new DatagramSocket (2222); System. out. println ("Chat Server started. "); while (true) {byte [] buffer = new byte [1024*16]; DatagramPacket recvPacket = new DatagramPacket (buffer, buffer. length); serverSocket. receive (recvPacket); InetSocketAddress remoteAddress = new InetSocketAddress (recvPacket. getAddress (), recvPacket. getPort (); System. out. println ("received" + remoteAddress. getHostString () + "sent packets"); byte [] data = recvPacket. getData (); byte [] recvData = new byte [recvPacket. getLength ()]; System. arraycopy (buffer, 0, recvData, 0, recvData. length); System. out. println (recvData. length); Map <String, Object> map = ChatClient. convertByteArrayToMap (recvData); System. out. print ("map length" + map. size (); if (map. containsKey ("onlineFlag") {// publish or deprecate boolean B = (boolean) map. get ("onlineFlag"); if (B) {// launch onlineIPs. add (remoteAddress. getHostString ();} else {// deprecate onlineIPs. remove (remoteAddress. getHostString () ;}} queue. add (map) ;}} catch (Exception e) {e. printStackTrace () ;}} public static void main (String [] args) {new ChatServer ();}}