Cet article décrit les fonctions de communication client et serveur implémentées par Java en fonction de Socket. Partagez-le pour votre référence, comme suit:
Le code suivant fait référence au projet de chat de MA Soldier. Exécutez d'abord ChatServer.java pour implémenter l'écoute du port, puis exécuter ChatClient.java.
Instance client
Chatclient.java
package socketdemo; import java.awt. *; import java.awt.event. *; import java.io. *; import java.net. *; public class chatClient étend le trame {socket s = null; DataOutputStream DOS = NULL; DatAnputStream dis = null; Boolean privé bconnected = false; TextField tftxt = new TextField (); TextArea tacontent = new TextArea (); Thread trecv = nouveau thread (new recvThread ()); public static void main (String [] args) {new ChatClient (). LaunchFrame (); } public void LaunchFrame () {setLocation (400, 300); this.setSize (300, 300); Add (tftxt, borderlayout.south); Add (tacontent, borderlayout.north); paquet(); this.addwindowListener (new WindowAdapter () {@Override public void windowClosing (windowEvent arg0) {disconnect (); system.exit (0);}}); tftxt.addactionListener (new tfListener ()); setVisible (true); connecter(); trecv.start (); } public void connect () {try {s = new socket ("localhost", 8888); DOS = new DataOutputStream (s.GetOutputStream ()); dis = new DatAnputStream (s.getInputStream ()); System.out.println ("Connected!"); bconned = true; } catch (inconnuhostException e) {e.printStackTrace (); } catch (ioException e) {e.printStackTrace (); }} public void disconnect () {try {dos.close (); divulguer(); S.Close (); } catch (ioException e) {e.printStackTrace (); } / * * essayez {bconned = false; Trecv.Join (); } catch (InterruptedException * e) {e.printStackTrace (); } enfin {try {dos.close (); divulguer(); * s.close (); } catch (ioException e) {e.printStackTrace (); }} * /} classe privée TfListener implémente ActionListener {public void ActionPerformed (actionEvent e) {String str = tftxt.getText (). Trim (); // tacontent.setText (str); tftxt.setText (""); essayez {// system.out.println (s); Dos.WriteUtf (STR); Dos.Flush (); // dos.close (); } catch (ioException e1) {e1.printStackTrace (); }}} classe privée recvThread implémente Runnable {public void run () {try {while (bconned) {string str = dis.readutf (); // System.out.println (STR); tacontent.setText (tacontent.getText () + str + '/ n'); }} catch (socketException e) {System.out.println ("exit, bye!"); } catch (eofException e) {System.out.println ("Exception, bye - bye!"); } catch (ioException e) {e.printStackTrace (); }}}}code de serveur de socket
Chatserver.java
package socketdemo; import java.io. *; import java.net. *; import java.util. *; public class Chatserver {booléen start = false; SERVERSOCKET SS = NULL; List <lient> Clients = new ArrayList <Simité> (); public static void main (String [] args) {new ChatServer (). start (); } public void start () {try {ss = new serversocket (8888); démarré = true; } catch (bindException e) {System.out.println ("Port In Use ......"); System.out.println ("Veuillez fermer le programme pertinent et relancer le serveur!"); System.exit (0); } catch (ioException e) {e.printStackTrace (); } essayez {while (démarré) {socket s = ss.accept (); Client C = nouveau client (s); System.out.println ("Un client connecté!"); nouveau thread (c) .start (); clients.add (c); // dis.close (); }} catch (ioException e) {e.printStackTrace (); } enfin {try {ss.close (); } catch (ioException e) {// TODO Bloc de capture généré automatiquement e.printStackTrace (); }}} Class Client implémente Runnable {private socket s; private datainputStream dis = null; DataOutputStream DOS = NULL; Boolean privé bconnected = false; Client public (socket s) {this.s = s; try {dis = new DatAnputStream (s.getInputStream ()); DOS = new DataOutputStream (s.GetOutputStream ()); bconned = true; } catch (ioException e) {e.printStackTrace (); }} public void Send (String str) {try {dos.writeUtf (str); } catch (ioException e) {clients.Remove (this); System.out.println ("L'autre partie est sortie! Je l'ai supprimée de la liste!"); // e.printStackTrace (); }} public void run () {try {while (bconned) {string str = dis.readUtf (); System.out.println (STR); pour (int i = 0; i <clients.size (); i ++) {client c = clients.get (i); C.Send (Str); // System.out.println ("A String Send!"); } / * * for (iterator <lient> it = clients.iterator (); * it.hasnext ();) {client c = it.next (); C.Send (Str); } * / / * * Iterator <lient> it = clients.iterator (); * while (it.hasnext ()) {client c = it.next (); C.Send (Str); *} * /}} catch (eofException e) {System.out.println ("Client fermé!"); } catch (ioException e) {e.printStackTrace (); } enfin {try {if (dis! = null) dis.close (); if (dos! = null) dos.close (); if (s! = null) {s.close (); // s = null; }} catch (ioException e1) {e1.printStackTrace (); }}}}}}Les résultats du test local:
Après la fermeture de la fenêtre du client, le message rapide est le suivant:
Pour plus d'informations sur le contenu lié à Java, veuillez consulter les sujets de ce site: "Résumé des compétences de programmation Java Socket", "Résumé des compétences de fichier Java et d'opération de répertoire", "Tutorial sur la structure de données Java et l'algorithme", "Résumé de l'opération Java Dom Skills" et "Résumé des compétences en opération de cache Java"
J'espère que cet article sera utile à la programmation Java de tous.