Este artigo descreve as funções de comunicação do cliente e do servidor implementadas pelo Java com base no soquete. Compartilhe -o para sua referência, como segue:
O código a seguir se refere ao projeto de bate -papo do MA Soldier. Primeiro, run chatserver.java para implementar a escuta por porta e depois execute chatclient.java.
Instância do cliente
Chatclient.java
pacote soketdemo; importar java.awt.*; importar java.awt.event.*; importar java.io.*; importar java.net. DataOutputStream DOS = null; DatainputStream Dis = NULL; Privado booleano bConnected = false; Textfield tftxt = new textfield (); Textarea tacontent = new textarea (); Thread trecv = new 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); pacote(); this.addwindowlistener (new windowAdapter () {@Override public void WindowClosing (WindowEvent arg0) {desconect (); System.exit (0);}}); tftxt.addactionListener (new tflistener ()); setvisible (true); conectar(); trecv.start (); } public void Connect () {try {s = new Socket ("localhost", 8888); DOS = new DataOutputStream (s.getOutputStream ()); DIS = new DatainputStream (s.getInputStream ()); System.out.println ("conectado!"); bConnected = true; } catch (desconhecidohostException e) {e.printStackTrace (); } catch (ioexception e) {e.printStackTrace (); }} public void desconect () {try {Dos.close (); divulgar(); S.Close (); } catch (ioexception e) {e.printStackTrace (); } / * * tente {bconnected = false; trecv.join (); } catch (interruptedException * e) {e.printStackTrace (); } finalmente {tente {Dos.close (); divulgar(); * S.Close (); } catch (ioexception e) {e.printStackTrace (); }} */} classe privada tflistener implementa ActionListener {public void ActionPerformed (ActionEvent E) {String str = tftxt.getText (). TRIM (); // tacontent.settext (str); tftxt.settext (""); tente {// system.out.println (s); Dos.Writeutf (STR); Dos.flush (); // dos.close (); } catch (ioexception e1) {e1.printStackTrace (); }}} classe privada RecvThread implementa Runnable {public void run () {try {while (bConnected) {string str = dis.readUtf (); // system.out.println (str); tacontent.settext (tacontent.getText () + str + '/n'); }} catch (Socketexception e) {System.out.println ("Exit, tchau!"); } catch (eofexception e) {system.out.println ("exceção, tchau - tchau!"); } catch (ioexception e) {e.printStackTrace (); }}}}Código do servidor de soquete
ChatServer.java
pacote soketdemo; importar java.io.*; importar java.net. Serversocket ss = nulo; List <Client> clientes = new ArrayList <SterMem> (); public static void main (string [] args) {new ChatServer (). start (); } public void start () {try {ss = new ServerSocket (8888); iniciado = true; } catch (bindException e) {System.out.println ("porta em uso ......"); System.out.println ("Feche o programa relevante e execute o servidor!"); System.Exit (0); } catch (ioexception e) {e.printStackTrace (); } tente {while (iniciado) {soquete s = ss.accept (); Cliente c = novo (s) cliente (s); System.out.println ("um cliente conectado!"); novo thread (c) .start (); clientes.add (c); // Dis.Close (); }} catch (ioexception e) {e.printStackTrace (); } finalmente {tente {ss.close (); } catch (ioexception e) {// TODO GATO GENERADO AUTOMENTADO BLOCO E.PRINTSTACKTRACE (); }}} classe cliente implementa Runnable {Setorgrafia privada S; DatainputStream privado Dis = NULL; DATATUTTUPTREAM PRIVADO DOS = NULL; Privado booleano bConnected = false; cliente público (soquete s) {this.s = s; tente {dis = new DatainputStream (s.getInputStream ()); DOS = new DataOutputStream (s.getOutputStream ()); bConnected = true; } catch (ioexception e) {e.printStackTrace (); }} public void send (string str) {try {dos.Writeutf (str); } catch (ioexception e) {clients.remove (this); System.out.println ("A outra parte saiu! Eu a removi da lista!"); // e.printStackTrace (); }} public void run () {try {while (bConnected) {string str = Dis.ReadUtf (); System.out.println (str); for (int i = 0; i <clients.size (); i ++) {client c = clients.get (i); C.send (STR); // System.out.println ("A String Send!"); } / * * para (iterator <fient> it = clients.iterator (); * it.hasnext ();) {client c = it.next (); C.send (STR); } * / / * * Iterator <ccruster> it = clients.iterator (); * while (it.hasnext ()) {client c = it.Next (); C.send (STR); *} */}} catch (eofexception e) {System.out.println ("Cliente fechado!"); } catch (ioexception e) {e.printStackTrace (); } finalmente {tente {if (dis! = null) dis.close (); if (dos! = null) dos.close (); if (s! = null) {s.close (); // s = null; }} catch (ioexception e1) {e1.printStackTrace (); }}}}}}Os resultados da execução do teste local:
Depois de fechar a janela do cliente, a mensagem imediata é a seguinte:
Para obter mais informações sobre o conteúdo relacionado a Java, consulte os tópicos deste site: "Resumo das habilidades de programação do soquete Java", "Resumo dos arquivos Java e habilidades de operação de diretório", "Tutorial sobre estrutura de dados Java e algoritmo", "Resumo da operação Java Dom Node Skills" e "Resumo de Java Cache Skills Skills Operation Skills"
Espero que este artigo seja útil para a programação Java de todos.