Recently, I have been taking the time to review some Java technology applications.
Nothing to do today, based on the UDP protocol, wrote a very simple chat room program.
Now work, rarely use socket, also is a Java network programming aspects of a simple memory.
First look at the effect:
The effect of implementation can be said to be very very simple, but still can be simple to see a principle of implementation.
"Chat room 001" Users, small red and small green chatted with each other, "chat room 002" Little black no one to ignore, in the side of loneliness.
Take a look at the code implementation:
1, the first is the implementation of the message server, the function is very simple:
• Registration of client information (which chat room is entered);
• Construct a UDP protocol socket object to accept messages sent by each client;
• Parsing the message content and pushing the chat information back to each client of the corresponding chat room;
Package com.tsr.simplechat.receive_server;
Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.SocketException;
Import java.util.ArrayList;
Import Java.util.HashMap;
Import Com.google.gson.Gson;
Import com.tsr.simplechat.bean.MessageEntity;
Import com.tsr.simplechat.client.ChatClient;
Chat server public class Chatserver extends Thread {//Program occupation port number private static final int port = 10000;
The message accepts the socket object private static Datagramsocket server = NULL;
Dictionary object (Key: Chat room Id,value: A collection of client users under this chat room); private static hashmap<string, arraylist<chatclient>> groups = new hashmap<string, arraylist<
Chatclient>> ();
Constructor public Chatserver () {try {//message accepts socket object's construction initialization server = new Datagramsocket (PORT);
catch (SocketException e) {e.printstacktrace (); }//Registered chat room New login user public static void Logingroup (String GroupID, chatclient client) {//through the chat room ID, get all online users of the chat room Arrayl ist<chatclient> clients = Groups.get (gROUPID);
if (clients = = NULL) {clients = new arraylist<chatclient> ();
///will enter the chat room user Registration Clients.add (client);
Update chat room Information Groups.put (GroupID, clients);
//loop Receive message @Override public void run () {while (true) {receivemessage ();
} private void ReceiveMessage () {//UDP packet byte[] buf = new byte[1024];
Datagrampacket packet = new Datagrampacket (buf, buf.length);
while (true) {try {//Accept packet server.receive (packet);
catch (IOException e) {//TODO auto-generated catch block E.printstacktrace ();
}//parsing packet, getting chat information string content = new String (Packet.getdata (), 0, Packet.getlength ());
Parsing JSON data through a third-party package Gson Gson = new Gson ();
messageentity me = Gson.fromjson (content, Messageentity.class);
Resolves the message content through the chat room ID to get all online users of the chat room arraylist<chatclient> clients = Groups.get (Me.getgroupid ());
Push the received message back to the individual user for this chat room for (chatclient client:clients) {client.pushbackmessage (me);
}
}
}
}
2, the client program, still very simple:
• Simple definition of the client chat room interface.
• Constructs a message-sending socket object.
• Get the contents of the Chat information box and send it to the server.
Package com.tsr.simplechat.client;
Import Java.awt.Button;
Import java.awt.Event;
Import Java.awt.Frame;
Import Java.awt.TextArea;
Import Java.awt.TextField;
Import Java.awt.event.WindowAdapter;
Import java.awt.event.WindowEvent;
Import java.io.IOException;
Import Java.net.DatagramPacket;
Import Java.net.DatagramSocket;
Import java.net.InetAddress;
Import java.net.SocketException;
Import java.net.UnknownHostException;
Import com.tsr.simplechat.bean.MessageEntity; Import Com.tsr.simplechat.receive_server.
Chatserver;
Client program public class ChatClient extends Frame {private static final long serialversionuid = 1L;
Chat room ID private String GroupID;
Client User name private String clientname;
Client message Send service socket private datagramsocket msg_send;
Service Port Private Final int PORT = 10000;
Server IP address private inetaddress IP;
Client control TextField tf = new TextField (20);
TextArea ta = new TextArea ();
button send = New button ("Send"); Client Builder Public ChatClient (string GroupID, String clientnAME) {super ("chat room:" + GroupID + "/" + ClientName);
This.clientname = ClientName;
This.groupid = GroupID;
Set Client interface style Add ("North", TF);
Add ("Center", TA);
Add ("South", send);
SetSize (250, 250);
Show ();
Chat-related server initialization init (); Monitor Addwindowlistener (new Windowadapter () {public void windowclosing (WindowEvent e) {//Turn off message forwarding service Msg_send.clos
E ();
Close the client program Dispose ();
System.exit (0);
}
});
}//Chat related server initialization private void init () {//register the current user and the chat room information registered to the server Chatserver.logingroup (GroupID, this);
try {//Initialize message send socket object msg_send = new Datagramsocket ();
Specifies the message server try {IP = inetaddress.getbyname ("127.0.0.1");
catch (Unknownhostexception e) {System.out.println ("Unknown host exception ...");
} catch (SocketException e) {System.out.println ("Socket connection exception ...");
}//Message send button Time Listener public boolean action (Event evt, Object Arg) {if (evt.target.equals (send)) {try {//Get input
String content = Tf.gettext ();
Send Message send_message (content); Empty chat Box Tf.setText (NULL);
catch (Exception IoE) {System.out.print (Ioe.getmessage ());
} return true;
}//Message send private void Send_message (String content) {//Message Format (JSON format) String message = Messageformat (content);
Encapsulates the message into a UDP packet byte[] buf = Message.getbytes ();
Datagrampacket packet = new Datagrampacket (buf, Buf.length, IP, PORT);
try {//Send message Msg_send.send (packet) via UDP protocol;
catch (IOException e) {System.out.println ("IO exception ...");
}//Message format private string Messageformat (string content) {StringBuffer buffer = new StringBuffer ();
Buffer.append ("{\" groupid\ ":"). Append ("\"). Append (GroupId). Append ("\");
Buffer.append ("\" username\ ": \"). Append (ClientName). Append ("\");
Buffer.append ("\" text\ ": \"). Append (content). Append ("\"});
return buffer.tostring ();
//Get current chat room update from server (callback ...)
public void Pushbackmessage (messageentity me) {ta.append (Me.getusername () + ":" + Me.gettext ());
Ta.append ("\ n");
}
}
3. Message entity class
The main thing is to encapsulate messages into objects, including: Chat room ID, message sender nickname, message content. Parse using JSON format.
Package Com.tsr.simplechat.bean;
Message entity Public
class Messageentity {
private String groupId;
Private String userName;
private String text;
Public String Getgroupid () {return
groupId;
}
public void Setgroupid (String groupId) {
this.groupid = groupId;
}
Public String GetUserName () {return
userName;
}
public void Setusername (String userName) {
this.username = userName;
}
Public String GetText () {return
text;
}
public void SetText (String text) {
this.text = text;
}
}
4, OK, here is basically done, set up a test class.
• Open the message server.
• Open three clients, of which two go to "chat room 001" and the other into "chat room 002".
Import com.tsr.simplechat.client.ChatClient;
Import Com.tsr.simplechat.receive_server. Chatserver;
public class Test {public
static void Main (string[] args) {
chatserver r = new Chatserver ();
R.start ();
ChatClient C1 = new ChatClient ("001", "Little Red");
ChatClient C2 = new ChatClient ("001", "Little Green");
ChatClient C3 = New ChatClient ("002", "small Black");
}
The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.