Java socket programming for group chat and private chat [schematic]

Source: Internet
Author: User

Brief introduction

using Java Sockets we can almost complete a web chat software small product, this article does not involve the UI part, only for the principle part of the code to demonstrate. A small, multi-person chat feature that is available on Linux systems with telnet affinity.

Server code
Package Demo0811.demo3;import Java.io.outputstream;import Java.net.serversocket;import java.net.Socket;import Java.util.arraylist;import Java.util.concurrent.executorservice;import java.util.concurrent.executors;/** * Use multithreading to write a server with port number 9999 * @author ZZW * */public class Servermain {public static arraylist<integer> ports=new ArrayList <Integer> ();p ublic static arraylist<outputstream> streams=new arraylist<outputstream> ();p ublic static void Main (string[] args) {try (ServerSocket server=new serversocket (9999)) {System.out.println ("server is Running"); Executorservice Newfixedthreadpool = Executors.newfixedthreadpool (+), while (true) {Socket socket = server.accept (); int port = Socket.getport (), OutputStream outputstream = Socket.getoutputstream ();p Orts.add (port); Streams.add ( OutputStream); Newfixedthreadpool.submit (new Socketrunnable (Socket,outputstream)); Newfixedthreadpool.submit (new Notifynewersrunnable (port));}} catch (Exception ex) {System.out.println ("Unable to establish monitoring service! "); ex.printstacktrAce ();} }}



Package Demo0811.demo3;import Java.io.bufferedreader;import Java.io.ioexception;import java.io.InputStream;import Java.io.inputstreamreader;import Java.io.outputstream;import Java.io.outputstreamwriter;import Java.net.Socket; Import Java.util.date;public class Socketrunnable implements Runnable {private Socket socket;private OutputStream Outputstream;public socketrunnable (Socket socket,outputstream outputstream) {this.socket=socket;this.outputstream= OutputStream;} @Overridepublic void Run () {try {outputstreamwriter outputstreamwriter = new OutputStreamWriter (outputstream);D ate Date = new Date (); Outputstreamwriter.write (date.tostring () + "\ n if sending private messages, use [port] to start with" + "\ r \ n"); Outputstreamwriter.flush (); int port = Socket.getport (), while (true) {if (socket.isconnected ()) {InputStream InputStream = Socket.getinputstream (); I Nputstreamreader reader = new InputStreamReader (InputStream, "UTF-8"); BufferedReader BufferedReader = new BufferedReader (reader); String Line;while ((Line=bufferedreader.readline ())!=null) {if (Line.startswith (")") {int end=line.indexof ('] '); int Target=integer.parseint (line.substring (1, end)); int IndexOf = ServerMain.ports.indexOf (target); if (end<0| | indexof<0) {OutputStreamWriter outputStreamWriter2 = new OutputStreamWriter (ServerMain.streams.get ( ServerMain.ports.indexOf (Port), "UTF-8"); Outputstreamwriter2.write ("Your private message format is incorrectly entered or the port number does not exist!") \ r \ n "); Outputstreamwriter2.flush ();} else {OutputStreamWriter OutputStreamWriter2 = new OutputStreamWriter (ServerMain.streams.get (indexOf), "UTF-8"); o Utputstreamwriter2.write ("Port" +port+ "Private Messages:" +line.substring (end+1) + "\ r \ n"); Outputstreamwriter2.flush ();}} else {for (int i=0;i<servermain.streams.size (); i++) {try {outputstreamwriter outputStreamWriter2 = new OutputStreamWriter (ServerMain.streams.get (i), "UTF-8"); Outputstreamwriter2.write ("Port" +port+ "group chat:" +line+ "\ n"); o Utputstreamwriter2.flush ();} catch (IOException e) {e.printstacktrace ();}}}} else {break;}} Socket.close ();} catch (IOException e) {System.out.println ("The server cannot write data to the client!") "); e.printstacktrAce ();} Finally {try {socket.close ();} catch (IOException e) {//Not processed}}}



Package Demo0811.demo3;import Java.io.ioexception;public class notifynewersrunnable implements Runnable{private int Port;public notifynewersrunnable (int port) {this.port = port;} @Overridepublic void Run () {int n; String str= "Port" +port+ "on line \ r \ n"; if ((N=servermain.streams.size ()) >1) {for (int i=0;i<n-1;i++) {try { ServerMain.streams.get (i). Write (Str.getbytes ("Utf-8")); ServerMain.streams.get (i). Flush ();} catch (IOException e) {e.printstacktrace ();}}}}



Java socket programming for group chat and private chat [schematic]

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.