Java-based chat room/Mass Control console program

Source: Internet
Author: User
Tags string format

Java chat Room 1, overview

TCP protocol-based, consisting of one server and multiple clients, one client sends messages, and all other clients can receive messages. A thread is set on the server side to listen for a request (message) from the client and respond to all clients. Each client also has a thread that is used to receive server-side requests.

2, the code is as follows

  

 Public classClient { Public Static voidMain (string[] args) throws IOException {//Creating SocketsSocket socket =NewSocket ("localhost",Bayi); //gets the output stream of the socketBufferedoutputstream BOS =NewBufferedoutputstream (Socket.getoutputstream ()); //start thread listening on receiving server-side messages        NewThread (Newclientmessage (socket)). Start (); Scanner SC=NewScanner (System.inch); //client sends a message         while(true) {String msg=Sc.nextline (); if("Exit". Equals (msg)) {                 Break; }            byte[] B =msg.getbytes (); Bos.write (b,0, b.length);        Bos.flush ();        } bos.close ();    Socket.close (); }}classClientmessage implements runnable{Privatesocket socket;  Publicclientmessage (socket socket) {super ();  This. Socket =socket; } @Override Public voidrun () {Try{Bufferedinputstream bis=NewBufferedinputstream (Socket.getinputstream ()); byte[] B =New byte[1024x768*8];  while(true){                inti =Bis.read (b); if(i = =-1){                     Break; } String msgfromserver=NewString (b,0, i); System. out. println (Msgfromserver);        } bis.close (); } Catch(IOException ex) {ex.printstacktrace (); }    }    }
public class Server {public static void main (string[] args) throws IOException {ServerSocket s = new ServerSocket (81);// Build a server socket, specify the port number list<socket> sockets = new arraylist<socket> (); SYSTEM.OUT.PRINTLN ("server Started"); int i = 0;for (; i <=; i++) {///can have 100 clients//Accept () is a blocking method that will not be executed if the client does not have a request to arrive. Immediately after the request arrives, a socket object is generated//listens for and receives the connection to this socket socket socket = s.accept ();//output the socket string format SYSTEM.OUT.PRINTLN (socket); Sockets.add (socket);//The boot thread is used to receive the message and mass new thread (new Chatmessage (socket, sockets)). Start ();}} Class Chatmessage implements Runnable {private Socket socket;private list<socket> sockets;public chatmessage ( Socket socket, list<socket> sockets) {super (); this.socket = Socket;this.sockets = sockets;} @Overridepublic void Run () {try {//Get the current socket input stream Bufferedinputstream bis = new Bufferedinputstream ( Socket.getinputstream ()); byte[] B = new byte[1024]; String msg = ""; while (true) {int i = Bis.read (b); if (i = =-1) {break;} Gets the message of the client msg = new String (b, 0, I);//Mass for (Socket s:sOckets) {out (S, socket.getinetaddress (). GetHostName () + ":" + msg);}}} catch (IOException e) {}}private void out (Socket s, String msg) {try {bufferedoutputstream bos = new Bufferedoutputstream ( S.getoutputstream ()); byte[] B = msg.getbytes (); Bos.write (b, 0, b.length); Bos.flush ();} catch (IOException e) {}}}

  

3. Summary

The server object ServerSocket is created first, and the port number is specified, and the ports cannot be occupied. It then calls its accept () method to listen for and receive a connection to this socket. This is the preparation for the server. The client needs to create the socket to specify the IP and port number to determine the corresponding server.

    

  

Java-based chat room/Mass Control console program

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.