The previous section of the current server only functions like the client sending data, and does not have the ability to read data from the client, we will make improvements in this section:
Create a new Chatmanager class:
Package Com.test.test;import Java.util.vector;public class Chatmanager {//Complete class Singleton: Private Chatmanager () {}private Static final Chatmanager cm=new Chatmanager ();p ublic static Chatmanager Getchatmanager () {return cm;} Complete the management of the Chatsocket thread:vector<chatsocket> vector=new vector<chatsocket> ();// Adds a new Chatsocket object to the current collection: public void Add (Chatsocket cs) {Vector.add (CS);} A thread can call the following function to send information like other clients public void publish (Chatsocket cs,string out) {for (int i = 0; i < vector.size (); i++) {Chatso Cket Cschatsocket=vector.get (i);//determines that the thread used for the current send will no longer receive this message if (!cs.equals (Cschatsocket)) {cschatsocket.out (out);}}}
Modify other Class 1:
Package Com.test.test;public class myServerSocket {public static void main (string[] args) {new Serverlistener (). Start ();}}
2:
Package Com.test.test;import Java.io.ioexception;import Java.net.serversocket;import java.net.socket;import Javax.swing.joptionpane;public class Serverlistener extends Thread {public void run () {try {ServerSocket serversocket= New ServerSocket (12345); while (true) {Socket socket=serversocket.accept (); Joptionpane.showmessagedialog (NULL, "There is a client connected to port 12345!") "); Chatsocket cs=new chatsocket (socket); Cs.start (); Chatmanager.getchatmanager (). Add (cs);}} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}}
3.
Package Com.test.test;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStream;import Java.io.inputstreamreader;import Java.io.unsupportedencodingexception;import Java.net.Socket;public Class Chatsocket extends Thread {socket socket;public chatsocket (socket s) {this.socket=s;} public void out (String out) {try {socket.getoutputstream (). Write (Out.getbytes ("UTF-8"));} catch ( Unsupportedencodingexception e) {//Todo auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {//Todo Au To-generated catch Blocke.printstacktrace ();}} public void Run () {try {BufferedReader br=new BufferedReader (New InputStreamReader (Socket.getinputstream (), "UTF-8")); String Line=null;while ((Line=br.readline ())!=null) {Chatmanager.getchatmanager (). Publish (this, line);} Br.close ();} catch (Unsupportedencodingexception e) {//TODO auto-generated catch Blocke.printstacktrace ();} catch (IOException e) {// TODO auto-generated catch Blocke.printstacktrace ();}}}
The class structure is as follows:
At this point we test, open three terminals, then connect, then enter the content, so that each client can receive messages sent by others:
android--Creating a network chat room using socket Communication 2