Using ServerSocket Communication in Java

Source: Internet
Author: User

1. Create a Java project Testmyserversocket.

2. Create a package Com.weloglog.main

3. Create some classes to use

Program Startup class Myserversccket: Used to start the program, after starting to create a process to monitor the local current port

Monitor native Port Process class Serverlistener: Used to monitor the local port, generates a chat class chatsocket when there is a connection to the native port and adds the chat class to the Chat management class (Singleton Class) Chatmanager

Chat class Chatsocket: Used to send messages to the Chat window (except for themselves)

Chat Management class Chatmanager: used to collect and manage all chat windows

4. The following are all class codes:

Myserversccket.java

 Package Com.weloglog.main;  Public class Myserversccket {    publicstaticvoid  main (string[] args) {         New Serverlistener (). Start ();    }}
View Code

Serverlistener.java

 PackageCom.weloglog.main;Importjava.io.IOException;ImportJava.net.ServerSocket;ImportJava.net.Socket;ImportJavax.swing.JOptionPane; Public classServerlistenerextendsThread {intPort = 12345; @Override Public voidrun () {Try {            //Port: 1-65535ServerSocket ServerSocket =NewServerSocket (port);  while(true) {                                //methods of blockingSocket socket =serversocket.accept (); //Establish a connectionJoptionpane.showmessagedialog (NULL, "There is a client connected to the native 12345 port"); //passing a socket to a threadChatsocket cs =Newchatsocket (socket);                Cs.start ();            Chatmanager.getchatmanager (). Add (CS); }        } Catch(IOException e) {e.printstacktrace (); }    }}
View Code

Chatsocket.java

 PackageCom.weloglog.main;ImportJava.io.BufferedReader;ImportJava.io.BufferedWriter;Importjava.io.IOException;ImportJava.io.InputStreamReader;ImportJava.io.OutputStreamWriter;Importjava.io.UnsupportedEncodingException;ImportJava.net.Socket; Public classChatsocketextendsThread {socket socket;  PublicChatsocket (Socket s) { This. Socket =s; }    //Send Message     Public voidout (String out) {Try{socket.getoutputstream (). Write (Out.getbytes ("UTF-8"));        System.out.println (out); } Catch(IOException e) {e.printstacktrace (); }} @Override Public voidrun () {Try{bufferedreader br=NewBufferedReader (NewInputStreamReader (Socket.getinputstream (),"UTF-8")); String Line=NULL;  while(line = Br.readline ())! =NULL) {Chatmanager.getchatmanager (). Publish ( This, line); }        } Catch(unsupportedencodingexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }    }}
View Code

Chatmanager.java

 PackageCom.weloglog.main;ImportJava.util.Vector; Public classChatmanager {//single-instance class    PrivateChatmanager () {}Private Static FinalChatmanager cm =NewChatmanager ();  Public StaticChatmanager Getchatmanager () {returncm; }        //the container that holds the chat processvector<chatsocket> vector =NewVector<chatsocket>(); //Add     Public voidAdd (Chatsocket cs) {Vector.add (CS); }        //Traverse Send Message     Public voidPublish (Chatsocket CS, String out) { for(inti = 0; I < vector.size (); i++) {Chatsocket Cschatsocket=Vector.get (i); //It 's not your own output .            if(!cs.equals (Cschatsocket))            {cschatsocket.out (out); }        }    }}
View Code

Using ServerSocket Communication in Java

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.