Java creates chat rooms (servers and clients)

Source: Internet
Author: User

Java creates a chat room (client)

/* Client connection (myclient. Java )*/
Package itbaby. jchat;
Import java.net .*;
Import java. Io .*;
Import java. AWT .*;
Import javax. Swing .*;

Public class myclient extends thread
{
Static socket server;
Textarea jtextarea1;
List list1;
Printwriter out;
Outputstream outs;
String susername;
String sipaddr;

Public myclient (textarea _ jtextarea1, LIST _ list1, string _ susername, string SIP)
{
This. jtextarea1 = _ jtextarea1;
This. list1 = _ list1;
This. susername = _ susername;
This. sipaddr = sip;
}

Public void sendmessage (string smessage) // send a public chat message
{
Out. println ("[" + this. susername + "]:" + smessage );
Out. Flush ();
}

Public void sendmessageprivate (string privateuser, string smessage) // send a private chat message
{
Out. println ("sendto:" + privateuser + "[" + this. susername + "]:" + smessage );
Out. Flush ();
}

Public void sendwelcome () // send a welcome message to the server, which is a message that is sent by the server.
{
Out. println ("cmd: Welcome" + susername );
Out. Flush ();
}

Public void run ()
{
Try
{
Myclient. Server = new socket (this. sipaddr, 2005 );
Outs = server. getoutputstream ();
Out = new printwriter (outs );

Myclientthread myct = new myclientthread (this. jtextarea1, this. list1 );
Myct. Start ();

This. sendwelcome ();

// Bufferedreader Wt = new bufferedreader (New inputstreamreader (system. In ));
/* While (true) // console-based test Client
{
String STR = wt. Readline ();
Out. println (STR );
Out. Flush ();
If (Str. Equals ("end "))
Break;
}
Out. Close ();
Server. Close ();*/
}
Catch (exception ex)
{
String exmsg = ex. getmessage ();
System. Out. println (exmsg );
}

}

Public static void main (string [] ARGs) throws exception
{

}

}

 

 

/* Client thread handler (myclientthread. Java )*/
Package itbaby. jchat;
Import java. Io .*;
Import java.net .*;
Import javax. Swing .*;
Import java. util .*;
Import java. Lang .*;
Import java. AWT .*;

Public class myclientthread extends thread
{
Textarea jtextarea1;
Java. AWT. List list1;
Public myclientthread (textarea _ jtextarea1, java. AWT. LIST _ list1)
{
This. jtextarea1 = _ jtextarea1;
This. list1 = _ list1;
}

Public void run ()
{

While (true)
{
Try
{
Bufferedreader in = new bufferedreader (New inputstreamreader (myclient. server. getinputstream ()));
String smsg = in. Readline ();
If (smsg. indexof ("cmd: userlist ")! =-1)
{
// User list
Smsg = smsg. substring (12, smsg. Length ());
This. list1.removeall ();
String susr = "";
For (INT I = 0; I <smsg. Length (); I ++)
{

If (smsg. charat (I) = '|') // user names are separated by |
{
This. list1.add (susr );
Susr = "";
}
Else
Susr = susr + String. valueof (smsg. charat (I ));
}

}
Else
This. jtextarea1.append (smsg + '/N'); // chat Information
}
Catch (exception ex)
{
String exmsg = ex. getmessage ();
System. Out. println (exmsg );
}
}
}

}

 

/* Briefly describe the Client GUI program, saving the GUI */

 

// After the system is loaded, click the login button to initialize the client connection.
Myclient mclient; // global class

 

// Textarea1 Message Display
// List1 user list
// Jtextfield1 message input area
// Jtextfield4 File Transfer Path Name
Mclient = new myclient (textarea1, list1, jtextfield1.gettext (), jtextfield4.gettext ());
Mclient. Start ();

// There Is A send button. When you click it, run the following code:
If (jtextfield2.gettext (). Length () = 0) return;
If (checkbox1.getstate () // Private Chat Information
{
If (jlabel4.gettext (). Length ()! = 0)
Mclient. sendmessageprivate (jlabel4.gettext (),
This. jtextfield2.gettext ());
}
Else // public chat
Mclient. sendmessage (jtextfield2.gettext ());

Jtextfield2.settext ("");

 

Java creates a chat room (server)

 

/* Server Master Program (myserver. Java )*/
Package itbaby. jchat;

Import java. Io. bufferedreader;
Import java. Io. ioexception;
Import java. Io. inputstreamreader;
Import java. Io. printwriter;
Import java.net. serversocket;
Import java.net. Socket;
Import java. util. arraylist;

Public class myserver
{
Static arraylist clients = new arraylist ();
Static arraylist onlineuser = new arraylist ();
Static arraylist onlineip = new arraylist ();
Public myserver ()
{
}

Public static void cleanuplistenlist ()
{
/*
Check the number of current online users, called in the thread
*/
For (INT I = clients. Size ()-1; I>-1; I --){
Myserverthread client = (myserverthread) clients. Get (I );
If (! Client. isalive ())
{
String sbye = "goodbye" + (string) onlineuser. Get (I );
Client. Kill ();
Clients. Remove (I); // remove a disconnected thread
Onlineuser. Remove (I );
Onlineip. Remove (I );
Myserverthread. sendtoalluser (); // update an online user
Myserverthread. sendtoall (sbye); // display the goodbye message
System. Out. println ("disconnected ...");
}
}

}

Public static void main (string argv []) throws ioexception
{
Serversocket listener = new serversocket (2005 );
Bufferedreader in = new bufferedreader (New inputstreamreader (system. In ));
Printwriter out = new printwriter (system. Out, true );

System. Out. println ("running ...");
System. Out. println ("port: 2005 ");
Myuserrefresh myuref = new myuserrefresh ();
Myuref. Start ();

While (true)
{
Socket Client = listener. Accept (); // wait for the client to connect
Myserverthread myclientthread = new myserverthread (client); // a connection is established to start executing a thread.
Myclientthread. Start ();
Myserver. Clients. Add (myclientthread); // record valid threads
Myserver. cleanuplistenlist ();
}

}

}

 

 

/* Chat thread handler (myserverthread. Java )*/
Package itbaby. jchat;
Import java. Io. bufferedreader;
Import java. Io. ioexception;
Import java. Io. inputstream;
Import java. Io. inputstreamreader;
Import java. Io. outputstream;
Import java. Io. printwriter;
Import java.net. Socket;
Import java. util .*;

Public class myserverthread extends thread
{
Private Socket Client;
Boolean stillrunning = true;
Public printwriter pout;

Public myserverthread (socket _ client)
{
Client = _ client;
}

Public void kill ()
{
Stillrunning = false;
}

Public static void sendtoall (string smsg) // public chat
{
For (INT I = 0; I <myserver. Clients. Size (); I ++)
{
Myserverthread th = (myserverthread) myserver. Clients. Get (I );
Th. Pout. println (smsg + "(" + Th. gettime () + ")");
}
}

Public void sendtoprivate (string sprivateuser, string smsg) // Private Chat
{
For (INT I = 0; I <myserver. Clients. Size (); I ++)
{
String sip = (string) myserver. onlineip. Get (I );
String sus = (string) myserver. onlineuser. Get (I );
String suser = sus + "(" + sip + ")";
If (sprivateuser. Trim (). Equals (suser. Trim ()))
{
Myserverthread th = (myserverthread) myserver. Clients. Get (I );
Th. Pout. println ("privatemessage:" + smsg + "(" + Th. gettime () + ")");
Break;
}
}

}

Public static void sendtoalluser () // all online user list data
{
String suser = "";
Int icount = myserver. Clients. Size ();
For (INT I = 0; I <icount; I ++)
{
String sip = (string) myserver. onlineip. Get (I );
String sus = (string) myserver. onlineuser. Get (I );
Suser = suser + sus + "(" + sip + ") | ";
}

For (INT I = 0; I <icount; I ++)
{
Myserverthread th = (myserverthread) myserver. Clients. Get (I );
Th. Pout. println ("cmd: userlist" + suser );
}

}

 

Public String gettime ()
{
// String stime = "";
Java. Text. dateformat format1 = new java. Text. simpledateformat ("HH: mm: SS ");
Java. util. Date currenttime_2 = new java. util. Date ();
String stime = format1.format (currenttime_2 );

Return stime;
}

Public String getclientip ()
{
Return (client. getinetaddress (). tostring ();
}

Public void run ()
{
Try
{
// (Client. getinetaddress (). tostring ());
Inputstream in = client. getinputstream ();
Inputstreamreader textin = new inputstreamreader (in );
Bufferedreader textlinein = new bufferedreader (textin );
Outputstream out = client. getoutputstream ();
Pout = new printwriter (Out, true );

While (stillrunning)
{

String sometext = textlinein. Readline ();
If (sometext. Length ()! = 0)
{
If (sometext. indexof ("cmd: Welcome ")! =-1)
{// Welcome Message
String suser = sometext. substring (11, sometext. Length ());
This. sendtoall ("welcome" + suser + "from" + this. getclientip ());

Myserver. onlineip. Add (this. getclientip ());
Myserver. onlineuser. Add (suser );

// Send User List Data
Myserverthread. sendtoalluser ();
}
Else if (sometext. indexof ("sendto :")! =-1)
{// Private Chat
String suser = sometext. substring (7, sometext. indexof (")") + 1 );
Sometext = sometext. substring (sometext. indexof (")") + 1,
Sometext. Length ());
Pout. println ("privatemessage:" + sometext + "(" + this. gettime () + ")"); // self-sent, self-echo chat statement
This. sendtoprivate (suser, sometext); // recipient, displaying chat statements
}
Else myserverthread. sendtoall (sometext); // send public chat messages

}
}

}
Catch (ioexception E)
{
System. Out. println ("I/O error they probably left" + E );
}

}

}

 

 

/* Refresh the user */
Package itbaby. jchat;

Public class myuserrefresh extends thread
{
Public myuserrefresh (){
}

Public void run ()
{
While (true)
{
Myserver. cleanuplistenlist ();
}
}
}

 

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.