Java Network Programming-a simple chat room program based on UDP protocol

Source: Internet
Author: User
Tags gettext

Recently more busy, has been taking time to review some Java technology applications.

Nothing to do today, based on the UDP protocol, wrote a very simple chat room program.

The current job, rarely used sockets, is also a simple memory of the Java network programming.

First look at the effect:

The effect of the implementation can be said to be very, very simple, but it is easy to see an implementation principle.

"Chat room 001" Users, small red and small green chat with each other, "chat room 002" of the small black unattended, 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 simple:

    • Register the client's information (into which chat room, etc.);
    • Constructs the UDP protocol socket object, accepts the message which each client sends;
    • Parse the message content, push the chat information back to the corresponding chat room client;
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 occupies port number private static final int PORT = 10000;//message accepts socket object private static Datagramsocket Server = null;//Dictionary object (Key: Chat room Id,value: Collection of client users under this chat room);p rivate Static hashmap<string, arraylist<chatclient>> groups = new hashmap<string, arraylist<chatclient> > ();//Constructor public Chatserver () {try {////message accepts the construction of the socket object to initialize Server = new Datagramsocket (PORT),} catch (SocketException e) {e. Printstacktrace ();}} Register 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 arraylist< chatclient> clients = Groups.get (GroupID), if (clients = = NULL) {clients = new arraylist<cHatclient> ();} Register the user who entered the chat room clients.add (client);//Update the chat room information groups.put (GroupID, clients);} Loop Receive Message @overridepublic void Run () {while (true) {ReceiveMessage ()}} private void ReceiveMessage () {//UDP packet byte[] buf = new byte[1024];D atagrampacket packet = new Datagrampacket (buf, Buf.le Ngth); while (true) {try {//Accept packet server.receive (packet);} catch (IOException e) {//TODO auto-generated catch Blocke.print StackTrace ();} Parse the packet, get the chat message string content = new String (Packet.getdata (), 0, Packet.getlength ());//parse the JSON data through a third-party package Gson Gson = new Gson ( ); messageentity me = Gson.fromjson (content, messageentity.class);//parse the message contents and get all the online users of the chat room through the chat room ID arraylist< chatclient> clients = Groups.get (Me.getgroupid ());//Push the received message back to the chat room for each user for (ChatClient client:clients) { Client.pushbackmessage (Me);}}}

2, the client program, still very simple:
    • Simply define the client chat room interface.
    • Constructs a message to send a socket object.
    • Gets the contents of the Chat message box, which is sent 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 idprivate S Tring 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 Constructor 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 ( (), show ();//chat Related server initialization init ();//Monitor Addwindowlistener (new Windowadapter () {public void windowclosing ( WindowEvent e) {//Close message sending service msg_send.close ();//Close client program Dispose (); System.exit (0);}}); Chat related server Initialize private void init () {//register current user and chat room information registered to server Chatserver.logingroup (GroupID, this); try {//Initialize message Send socket object Msg_ send = new Datagramsocket ();//Specify the message server try {IP = inetaddress.getbyname ("127.0.0.1");} catch (Unknownhostexception e) {Syst Em.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 sent by private void Send_message (string content) {///Message Format (JSON format) String message = Messageformat (content);//package message as UDP packet byte[] buf = message.getbytes ();D atagrampacket packet = new Datagrampacket (buf, Buf.length, IP, P ORT); try {//Send message Msg_send.send (packet) via UDP protocol,} catch (IOException e) {System.out.println ("IO exception:");}} Message formatting 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 the current chat room latest message from the server (callback:) public void Pushbackmessage (messageentity me) {ta.append (Me.getusername () + ":" + Me.gettext ()); Ta.append ("\ n");}}

3. Message entity class
It is mainly used to encapsulate messages into objects, including: Chat room ID, message sender nickname, message content. Parsed 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.
    • Turn on the messaging server.
    • Open three clients, two of which go to "chat room 001" and the other to "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", "small green"); ChatClient C3 = New ChatClient ("002", "small Black");}}

Source


Java Network Programming-a simple chat room program based on UDP protocol

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.