Java-based simple chat tools

Source: Internet
Author: User

Today, when I sorted out the materials, I found out a simple chat tool I used when I first learned Java a few years ago. Some servers and clients can send text messages and files, however, the user is not stored in the database online, but simply cached in an array of the server. Therefore, as soon as the server is closed, all user data will disappear. The interface uses a third-party package, which is very simple, ugly.


Source Code address: http://download.csdn.net/detail/weidi1989/5810475

(The gb2312 encoding method is based on jdk1.7. If there is a problem with importing eclipse directly, please solve it on Baidu, 3q)


Before running the code, we need to configure it first:

① Server configuration: As shown in, find the constants. Java file to open and change server_ip to the corresponding IP address of your computer. The port is changed as needed.


② Client configuration: As shown in, find the constants. Java class and change server_ip and server_port to correspond to the server (this is important)


③ Run the server before running the client.



Next, let's take a look at the details:

1. Run the server first, and then run the client. The following interface is displayed. users in the same LAN are automatically added to the friends list.



2. Test text chat. It simply sends text messages, so it is ugly.



3. send and receive test files. Ignore the content of the sent files!



Analysis of simple ideas:

① The server listens to a port and waits for a user's connection from time to time. When a user goes online, after several handshakes, the user is saved to an online user cache: usercache.

② Text messages are forwarded by the server. The user first encapsulates text messages into an object (this object contains the text message content, the IP address from which the message is sent, and the IP address to which the message is sent) and sends it to the server, the server then traverses the IP address of the object to be sent from the online user cache and forwards the IP address to the user, which completes the forwarding. This is similar to QQ chat on the Android-like mobile phone.

③ File transmission is a separate connection between users. When one party wants to send a file to the other party, it first forwards the file size, name, and other information through the server to inform the other party whether to receive the file, if the other party receives the message, it starts a socket for listening to file transfers, and then returns the information (also forwarded through the server) to the other party, at this time, start a thread socket to connect to the other party to send the file (in the middle, it is best to add a timeout judgment, I am very simple here, there is no processing ). In addition, I am updating the interface through swingworker, which is a bit similar to the android asynctask. It should be clear that I have done Android shoes.


Because the code is a long time ago and some details will inevitably be forgotten, I will not analyze the detailed code for you. It is actually very simple, if you want to learn more about shoes, you can download the source code for reference. Let's take a look at the two important parts of the Code:

Server. Java:

/*** Server, accepting user logon and offline ** @ author way **/public class server {private serversocket = NULL; private usercache = usercache. getinstance (); // user cache private transffer = new transfferimpl (); Private Boolean isstarted = true; public server () {inetaddress address; try {address = inetaddress. getbyname (constants. server_ip); serversocket = new serversocket (constants. server_port, 0, Ddress);} catch (unknownhostexception e) {// todo auto-generated catch blocke. printstacktrace (); system. exit (0);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace (); system. exit (0) ;}} public void start () {While (isstarted) {try {Socket socket = serversocket. accept (); tranobject object = transffer. get (socket); process (socket, object);} catch (ioexception e) {// todo auto-Genera Ted catch blocke. printstacktrace ();} catch (classnotfoundexception e) {// todo auto-generated catch blocke. printstacktrace () ;}}/ *** processes user requests ** @ Param socket * @ Param object */private void process (Socket socket, tranobject object) {llogger.info ("receives user messages! "); Switch (object. getType () {Case login: Login (socket, object); break; Case logout: Logout (socket, object); break ;}}/*** log on, after logging on, you must notify all online users of * @ Param socket * @ Param object */private void login (Socket socket, tranobject object) {llogger.info ("User Logon:" + object. getfromuser (). getip (); usercache. add (object. getfromuser (); tranobject <set <user> O = new tranobject <set <user> (tranobjecttype. login); O. settouser (object. getfromuser (); O. setobject (usercache. get (); try {transffer. tran (socket, O);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} // The tranobject <user> logino = new tranobject <user> (tranobjecttype. login); logino. setobject (object. getfromuser (); broadcast (logino);}/*** offline, after going offline, notify all online users * @ Param socket * @ Param object */private void logout (Socket socket, tranobject object) {llogger.info ("User offline:" + object. getfromuser (). getip (); usercache. delete (object. getfromuser (); // The tranobject <user> logouto = new tranobject <user> (tranobjecttype. logout); logouto. setobject (object. getfromuser (); broadcast (logouto);}/*** send broadcast package ** @ Param object */private void broadcast (tranobject object) to all online users) {set <user> set = usercache. get (); For (User U: Set) {object. settouser (U); try {transffer. trannoresponse (object);} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (classnotfoundexception e) {// todo auto-generated catch blocke. printstacktrace () ;}} public static void main (string [] ARGs) {new server (). start ();}}

The following is client. Java:

/*** The client * needs to be started: * 1. client Message Server listener * 2. message processor * 3. log on to the ** @ author way **/public class client {private user = new user (); Private clientsender sender = clientsenderimpl. getinstance (); Private messageprocessor = new messageprocessor (); // message processor private clientserver server; // message listener private mainframe frame = new mainframe (this ); private cache = cache. getinstance (); Public Client (String name) {user. setname (name); User. setport (constants. client_server_port); string IP = ""; try {IP = getip ();} catch (unknownhostexception E1) {e1.printstacktrace ();} If (IP = NULL | IP. equals ("") {joptionpane. showmessagedialog (null, "An error occurred while obtaining the IP address of the local machine! "); Return;} user. setip (IP); cache. setnowuser (User); If (! Login () {joptionpane. showmessagedialog (null, "cannot establish a connection with the server! "); Return;}/*** start message processor */messageprocessor.exe cute ();/*** start server */try {Server = new clientserver(frame,ip;{server.exe cute ();} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace (); joptionpane. showmessagedialog (null, "the port is occupied, and the program exits! "); System. exit (0);} // display the main window // awtutilities. setwindowopacity (frame, 1f); frame. addwindowlistener (New windowlistener () {@ overridepublic void windowopened (expose wevent e) {// todo auto-generated method stub} @ overridepublic void windowclosing (expose wevent E) {}@ overridepublic void windowclosed (invalid wevent e) {// todo auto-generated method stubsystem. exit (0) ;}@ overridepublic void incluwiconified (incluwevent E) {// todo auto-generated method stub} @ overridepublic void windowdeiconified (using wevent e) {// todo auto-generated method stub} @ overridepublic void windowactivated (using wevent E) {// todo auto-generated method stub} @ overridepublic void windowdeactivated (invalid wevent e) {// todo auto-generated method stub}); frame. setvisible (true);} private string getip () throws unknownhostexception {string IP = ine Taddress. getlocalhost (). gethostaddress (); Return IP;}/*** exit Operation * @ return */Public void logout () {llogger.info ("the user logs out! "); Sender. logout ();}/*** login */private Boolean login () {try {set <user> userset = NULL; userset = sender. login (); frame. getcenterpanel (). adduser (userset); Return true;} catch (ioexception e) {// todo auto-generated catch blocke. printstacktrace ();} catch (classnotfoundexception e) {// todo auto-generated catch blocke. printstacktrace ();} return false;} public static void main (string [] ARGs) {uimanager. put ("swing. boldmetal ", Boolean. false); new client ("test ");}}

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.