Java Chat Program

Source: Internet
Author: User

Package Cn.apr.chart;

Import java.net.*;
Import java.io.*;
Import java.util.*;

public class Chatserver {
/**
* @param args
* M_threads is a vector static variable that maintains all server-side Serverthread objects,
* This variable can be Chatapplet broadcast information to all the chat participants who have joined the chat room and revoke the exiting chat.
* The Main method of Chatserver the chat Service person. This method listens for the Chat applet's request and creates a service thread for the newly connected chat user.
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
ServerSocket socket = NULL;
Vector m_threads = new vector ();
System.out.println ("Listen ...");
try {
Set the ServerSocket listener port number to 5555, which must be the same as the port parameter in the program chat Chatapplet
Socket = new ServerSocket (5555);
} catch (Exception e) {
System.out.println ("New ServerSocket () failed!");
Return
}
try {
int nid = 0;
while (true) {
Monitor if there is a new chat applet attached to the chat server,
The thread runs to the statement that is blocked until a new connection is generated
Socket s = socket.accept ();
SYSTEM.OUT.PRINTLN ("accepted");
Create a new Serverthread
Serverthread st = new Serverthread (s, m_threads);
Set an ID number for the thread
St.setid (nid++);
Adding a thread to the m_threads vector
M_threads.addelement (ST);
Start the service thread
New Thread (ST). Start ();
Notify all Chatapplet have a new netizen to join
for (int i = 0; i < m_threads.size (); i++) {
Serverthread st1 = (serverthread) m_threads.elementat (i);
St1.write ("<#>welcome" + st.getid () + "to enter chatroom!");
}
System.out.println ("Listen again ...");
}
} catch (Exception e) {
System.out.println ("Server is down ...");
}
}
}

Listen to the thread, listen to the corresponding chat applet if there is information coming
Class Serverthread implements Runnable {
Vector m_threads;
Socket m_socket = null;
DataInputStream m_in = null;
DataOutputStream m_out = null;
int M_nid;

Initializing threads
Public Serverthread (Socket s, Vector threads) {
M_socket = s;
M_threads = threads;
try {
Constructing data input and output stream objects
m_in = new DataInputStream (M_socket.getinputstream ());
M_out = new DataOutputStream (M_socket.getoutputstream ());
} catch (Exception e) {
}
}

public void Run ()//thread's execution body
{
SYSTEM.OUT.PRINTLN ("Thread is running");
try {
while (true) {
Listen to the corresponding Chatapplet whether the message came
Thread is blocked in M_in.readutf () until a message comes back
String s = M_in.readutf ();
if (s = = null)
Break
If the message from the chat applet is "Leave", notify all other Chatapplet to launch their own
if (S.trim (). Equals ("Leave"))
for (int i = 0; i < m_threads.size (); i++) {
Serverthread st = (serverthread) m_threads.elementat (i);
St.write ("* * *" + GetID () + "Leave ..." + "* * *");
}
Else
Broadcast the message to all Chatapplet
for (int i = 0; i < m_threads.size (); i++) {
Serverthread st = (serverthread) m_threads.elementat (i);
St.write ("<" + GetID () + ">" + s);
}
}//while (true)
} catch (Exception e) {
E.printstacktrace ();
}
Remove the thread from the M_threads vector, indicating that the thread has left the chat room
M_threads.removeelement (this);
System.out.println ("Remove element!");
try {
M_socket.close ();
} catch (Exception e) {
}
}

Send msg back to the corresponding applet
public void Write (String msg) {
Synchronized (msg) {
try {
M_out.writeutf (msg);
} catch (IOException e) {
}
}
}

public int GetID ()//Get the ID of the thread
{
return M_nid;
}

public void SetID (int nid)//Set the ID of the thread
{
M_nid = nid;
}
}

//////////////

Package Cn.apr.chart;

Import java.awt.*;
Import java.applet.*;
Import java.io.*;
Import java.net.*;

Inherit applets, implement Runnable
public class ChatApplet1 extends Applet implements Runnable {
TextArea M_textarea; Accept Message Display window
TextField M_textfield; Send Message Input window
DataInputStream m_in; Message input stream
DataOutputStream M_out; Message output stream

/**
* @param args
* Initialization method of Chatapplet
*/
public void init () {
Create window
SetLayout (NULL);
SetSize (426, 266);
M_textarea = new TextArea (10, 10);
M_textfield = new TextField ();
m_in = null;
M_out = null;
Initialize the Appleton and connect to the Chat Service person
try {
Gets the URL of the applet, which is the server address
URL url = getcodebase ();
Get Server IP Address
InetAddress inetaddr = Inetaddress.getbyname (Url.gethost ());
Socket M_socket;
The screen displays the server IP address, the communication protocol
System.out.println ("Server:" + inetaddr + "" + url.gethost () + ""
+ Url.getprotocol ());
Create a socket that is connected to the server IP address, 5555 is the chat server socket interface Port
M_socket = new Socket (inetaddr, 5555);
Establishing an input stream on a socket interface
m_in = new DataInputStream (M_socket.getinputstream ());
Establishing an output stream on a socket interface
M_out = new DataOutputStream (M_socket.getoutputstream ());
} catch (Exception e) {
System.out.println ("Error:" + e);
}
SetLayout (New BorderLayout ());
Add ("Center", M_textarea);
Add ("South", M_textfield);
M_textarea.seteditable (FALSE);
Start the listener thread
New Thread (This). Start ();
}

When the chat type enters enter in the message input window, the string is read and sent to the Chat Service person.

public boolean Handleevent (event event) {
String B = M_textfield.gettext ();
if ((Event.target = = M_textfield) && (event.id = = event.action_event)) {
M_textfield.settext ("");
Send the message that the chat person entered to Chatserver
try {
M_out.writeutf (b); Send a uft format string to a chat service person
} catch (IOException e) {
}
return true;
} else
Return Super.handleevent (event);
}

The chat listener listens to the corresponding service thread, reads the message corresponding to the service line Cheng, and displays it in the Communication display window.

public void Run () {
try {
while (true) {
The chat listener listens for messages sent from the corresponding service thread, and it is blocked in the statement until the message arrives
String s = M_in.readutf (); Read a UTF format string
if (s! = null)
Display messages in the Information display window
M_textarea.append (s + "\ n");
}
} catch (Exception e) {
M_textarea.append ("Network problem or Server down.\n");
M_textfield.setvisible (FALSE);
}
}

public void Stop () {
try {
M_out.writeutf ("Leave");
} catch (IOException e) {
}
}

public static void Main (string[] args) {
TODO automatically generate method stubs
}
}

Java Chat Program

Related Article

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.