Making ICQ with Java

xiaoxiao2021-03-06  47

This is a material I found online. We also downloaded Snowingximen in www.9cbs.net, I hope to get a point induced from it. The code is not seen, the typography has made a little bit, please forgive me! I also hope that everyone can propose their own ideas.

Make ICQ with Java ---------------------------------------------------------------------------------------------------------------------------------------------------- ---------------------------------- author: Anonymous

Analyze the ICQ system and try to write with Java. One. The preambular ICQ is the abbreviation of English "I seek you", meaning in Chinese means looking for you. The biggest function of ICQ is the instant information communication. Just remember the number of the other party, you can call him when you go online, no matter where he is open, you can open your ICQ. ICQ is from Mirabils of Israel Tel Aviv. The company was established in July 1996, which is at this time, the most famous, the most downloaded free software ICQ is born. It may be its increasing user and broad prospects and extensive application prospects and huge market potential, Mirabils' ICQ is finally acquired by the US online AOL. Due to the success of ICQ, it has pushed the localization of ICQ. For Chinese ICQ, there is now more and more, such as the famous Shenzhen Tengxun launched OICQ (now because of copyright issues, it has been renamed QQ2001), and Tomq from Tom.com, etc., these software technology are very good, and it is easy to use, making it the favorite communication software of China Internet users.

However, these companies only provide software client programs free download without providing its server programs, so these software can not be used for private networks that are not connected to the Internet. Of course, there is also a free similar to ICQ server, but there are no source programs, even if there is, it is very simple, I really want to know what it is going, so I tried it.

two. design

1. Why choose Java? Java is a programming language for Sun Microsystem's James Gosling development. It is based on C , but it is a new software development language. Java is a simple, iconic object, distributed, interpretative, strong, safe, unrelated, portable, high-performance, multi-threaded and dynamic language ----- This is the definition of Sun to Java.

Sun's slogan is "Network is computer", Java can make all things calculated from desktop to the network-based calculation, it is specifically established for this, and it is obviously to complete this task. Using Java, we can write a conditional network program relatively easy day. Today, Java's network function is leaping. On the basis of increasing new features to this valuable, the Javasoft Lab is constantly making Java more perfect.

2. The database design system can adopt any popular, Java supported database, which uses Microsoft's SQL Server2000 as a background database. Through the reference to some of the current ICQ, establish a database, named javaicq, a database, a total of two tables, one is the basic information of the user, including the JICQ number, etc. One is the user's friend table, including the user's own number and the number of your friends.

(1) User's basic information table (table name ICQ) Sequence number field name enabling the data type NULL 1 ICQNO user's number INT No 2 Nickname User's CHAR NO 3 Password user password Char No 4 STATUS User Overline Yun Bit NO 5 IP User's IP Address Char Yes 6 Info User Information VARCHAR YES 7 PIC User's avatar Int Yes 8 SEX User Gender CHAR YES 9 Email User's Email CHAR YES 10 Place User's born char yes where ICQNO field is automatically increased. (Others can also add fields such as telephone numbers as more options) (2) User's Friends Table (Table name Friend) Sequence field name enclosure data type Null 1 ICQNO user's number INT NO 2 Friend Friends Number INT NO

3. System mode and program (Specific program visual source program) 1. Server program:

The server is connected to the client through a socket Socket (TCP). The use of the socket in Java is quite simple, and the Java API provides a class java.net.socket for the communication of the handling socket. Make the write network application is relatively easy. The server uses multi-threaded to meet multi-user requests, through the JDBC and the background database, and by creating a Serversocket object, the default port is 8080, then the accept () method accepts the Accept () method to accept the client.

The server program code is as follows: (some)

Import java.io. *; import java.net. *; import java.sql. *; import java.util.Vector; Class ServerThread Extends thread {// Inherited Thread Private Socket Socket; // Define Set of Sets of Interface Private BufferedReader IN; / / Define input traffic private printwriter out; // Define Output Stream INT NO; // Defining the JICQ Number Public Server ServerThread (Socket S) THROWS IEXCEPTION {// Throw Construction Function Socket = S; // Get Transfer Parameters IN = NEW BufferedReader (new InputStreamReader (socket.getInputStream ())); // Create input stream out = new PrintWriter (new BufferedWriter (new OutputStreamWriter (socket.getOutputStream ())), true); // create output stream start (); / / Start thread}

Public void run () {// thread monitor function try {while (true) {string str = in.readline (); // acquire input string IF (str.equals ("end")) Break; // If it is Close the connection ELSE IF (Str.Equals ("Login")) {// If you are logged into try {class.forname ("sun.jdbc.odbc.jdbcodbcdriver); // Connect the database Connection C = DriverManager.getConnection "JDBC: ODBC: Javaicq", "", ""); string sql = "SELECT NICKNAME, Password from icq where icqno =?"; // Preparing to select from the database, called and password preparedState PREPARE = ​​C.PRepareCall (SQL) ; // Set the database check condition string iCQNO = in.readline (); int g = integer.parseint (ICQNO); // get the entered JICQ number system.out.println (ICQNO); string passwd = in.readline ) .trim (); // acquire the input password system.out.println (passwd); prepare.clearparameters (); prepare.setint (1, g); // Setting parameters resultset r = prepare.executeQuery (); // Execute a database check IF (R.Next ()) {// The following comparison input number is on the password is the same String pass = r.getstring ("password"). Trim (); system.out.println (pass); if (Passwd.RegionMatches) (0, pass, 0, pass.Length ())) {OUT.PRINTLN ("OK"); // If you tell the customer OK / / / / and update the database user is online // and the IP address of the registered user // ************* Register ipaddress string setip = "Update ICQ SET IP =? WHERE ICQNO =?"; pretedStatement Prest = C.PrepareCall (setip); Prest.clearParameters ();

Prest.setString (1, socket.getinetdress (). gethostaddress (); Prest.setint (2, g); int set = preSt.executeUpdate (); system.out.println (SET); // **** ********* ipaddress // set status online string status = "update icq set status = 1 where ICQNO =?"; pretedStatement Prest2 = c.PrepareCall (status); Prest2.clearparameters (); Prest2.setInt (1, g); int set2 = PREST2.EXECUTEUPDATE (); system.out.println (set2); // set online} // no person tells customers to fail else out.println ("false"); R.Close ); c.close (); else {outputln ("false"); system.out.println ("false"); r.close (); C.close ();}} catch (exception e) {E.PrintStackTrace ();} Socket.close ();} // end login // End

/ / The following is to deal with the new request ELSE IF (Str.Equals ("Sun.jdbc.forname) {Try {class.forname (" Sun.jdbc.odbc.jdbCodbcDriver); // Connect Database Connection C2 = DriverManager.getConnection "JDBC: ODBC: Javaicq", "", "); String Newsql =" Insert ICQ (Nickname, Password, Email, Info, Place, PIC) VALUES (?,?,?,?,?,?) ; // Prepare for acceptance, password, email, personal data, biusing, avatar, etc. PREPAREDSTATEMENT PREPARE2 = C2.PrepareCall (newsql); string nickname = in.readLine (). Trim (); string password = in. Readline (). Trim (); String email = in.readline (). Trim (); string info = in.readline (). Trim (); string place = in.readline (). Trim (); int picindex = Integer.Parseint (In.Readline ()); prepare2.clearparameters (); prepare2.setstring (1, nickname); prepare2.setstring (2, password); prepare2.setstring (3, email); prepare2.setstring (4, INFO; prepare2.setstring (5, place); prepare2.setint (6, picindex); int R3 = preted2.executeUpdate (); // Execute Database Add String SQL2 = "SELECT ICQNO from ICQ WHERE NICKNAME =?"; / / The following tell customers its registration number PreparedStatement prepare3 = c2.prepareCall (sql2); prepare3.clearParameters (); prepare3.setString (1, nickname); ResultSet r2 = prepare3.executeQuery (); while (r2.next ()) {//Out.println (R2.Getint (1)); no = r2.Getint (1); system.out.println (no);} out.println (no); out.println ("OK"); C2.close (); // Entry} catch (exception e) {E.PrintStackTrace (); out.println ("false");} Socket.close ();} // end new // New user end // The following processing users find friends else if (Str.Equals ("Find")) {Try {class.forname ("

Sun.jdbc.odbc.jdbcodbcdriver "); Connection C3 = DriverManager.getConnection (" JDBC: ODBC: Javaicq "," "," "); // The following connection database, and return other users, said, gender, gender, Information, String Find = "Select Nickname, SEX, Place, IP, Email, Info from ICQ"; Statement St = C3.CreateStatement (); ResultSet Result = St.executeQuery (Find); while (result.next () ) {Out.Println ("nickname"); out.println (Result.getstring ("SEX")); Out.Println (Result.getstring ("Place")); Out.println (Result. GetString ("IP")); Out.Println (Result.getstring ("email"); out.println (Result.getstring ("info"));} // while end.println ("over"); GET ICQNO INT D, X; Boolean Y; / / The following returns the user's JICQ number, the avatar number, and whether online resultset iset = st.executeQuery ("SELECT ICQNO, PIC, STATUS from ICQ"); while (ist.next )) {D = ist.Getint ("ICQNO"); OUT.Println (D); x = ISET.GETINT ("PIC"); // pic info output.println (x); y = iet.getBoolean (" Status "); if (y) {out.println (" 1 ");} else {ou T.Println ("0");} //system.out.println (D);} // end send jicqno it.close (); / icqno end c3.close (); result.close ();} catch (Exception E) {E.PrintStackTrace (); System.out.Println ("false");} //socket.close ();} // end Find / / Find Friends End // Read the following to read the user login Its friend information ELSE IF (Str.Equals)) {Try {class.Forname ("Sun.jdbc.odbc.jdbcodbcdriver"); Connection C4 = DriverManager.getConnection ("JDBC: ODBC: Javaicq", "" "" "); // below to connect a good friend table,

Returns the user's buddy list String friend = "select friend from friend where icqno =?"; PreparedStatement prepare4 = c4.prepareCall (friend); prepare4.clearParameters (); int icqno = Integer.parseInt (in.readLine ()); System .out.println; prepare4.setint (1, ICQNO); ResultSet R4 = prepare4.executeQuery (); Vector FriendNo = New Vector (); // This vector saves friends number while (r4.next ()) { Friendno.add (NEW INTEGER (R4.Getint (1))));} // read friend info // The following tells the customer's name, number, IP address, status, avatar, personal information, etc. Out.Println Friendno.size ()); for (int i = 0; i

} // End Friend // Read Friends Information Double // The following handler adds friends ELSE IF (Str.Equals ("addfriend")) {system.out.println ("add"); try {class.forname (" Sun.jdbc.odbc.jdbcodbcdriver "); Connection C6 = DriverManager.getConnection (" JDBC: ODBC: Javaicq ",", ""); // Connect the database, add a record to your friend table according to the accepted user number and friend number int friendicqno = Integer.parseInt (in.readLine ()); System.out.println (friendicqno); int myicqno = Integer.parseInt (in.readLine ()); System.out.println (myicqno); String addfriend = " insert into friend values ​​"(,??); PreparedStatement prepare6 = c6.prepareCall (addfriend); prepare6.clearParameters (); prepare6.setInt (1, myicqno); prepare6.setInt (2, friendicqno); int r6 = 0; R6 = prepare6.executeUpdate (); if (r6 == 1) System.out.Println ("OK AddFrien"); Else System.Out.println ("false addfriend");} catch (exception e) {E.PrintStackTrace (); System.out.Println ("false");} //socket.close (); system.out.println ("over addfriend");} // end AddFriend // User Add Friends End // Add New Friend Who Add ME // The following to handle other users if you add me, I will add him else if (Str.Equals ("addnewfriend")) {system.out.println ("Add "); Try {class.forname (" sun.jdbc.odbc.jdbcodbcdriver "); Connection C6 = drivermanager.getConnection (" JDBC: ODBC: Javaicq ",", ""); // Connect the database, according to acceptable User Number and Friends Number Add Record INT Friendicqno = Integer.Parseint (In. Readline (); Int Myicqno = Integer.Parseint (In. Readline ()); System.out ()); System.out ()); System.out ()); System.out ()); system.out .println (myicqno); string addfriend =

"Insert into friend values ​​(,??)"; PreparedStatement prepare6 = c6.prepareCall (addfriend); prepare6.clearParameters (); prepare6.setInt (1, myicqno); prepare6.setInt (2, friendicqno); int r6 = 0 R6 = prepare6.executeUpdate (); if (r6 == 1) System.out.Println ("OK AddFrien"); Else System.Out.println ("false addfriend"); string friendinfo = "SELECT NICKNAME, ICQNO, IP, STATUS, PIC, EMAIL, INFO from ICQ WHERE ICQNO =? "; // If success, pass the basic information of friends to the user, such as the like preparedStatement prepare5 = c6.prepareCall (FriendInfo); prepare5.clearparameters () Prepare5.setint (1, Friendicqn); ResultSet R5 = prepare5.executeQuery (); Boolean Status; While (r5.next ()) {System.out.Println ("DSF"); Out.Println (r5.getstring "nickname"); out.println (r5.Getint ("ICQNO")); out.println (R5.GetString ("IP")); status = r5.getBoolean ("status); if (status) OUT .println ("1"); else {OUT.PRINTLN ("0"); Out.println (R5.Getint ("PIC")); Out.println (R5.GetString ("email"); out.println (r5.getstring ("info"));} // while out.println ("over"); r5.close (); c6.close ();} catch (exception e) {E.PrintStackTrace (); System.out.Println ("false");} system.out.println (" Over AddNewFriend ");} // end addfriend // End Processing Other users If you add me, I will add his // delete friends // below to perform the user to remove friends else if (Str.Equals (" Delfriend ") {system. Out.println ("DEL"); try {class.forname ("Sun.jdbc.odbc.jdbCodbcdriver");

Connection C7 = DriverManager.getConnection ("JDBC: ODBC: Javaicq", "", ""); // Connect the database, delete record int matchicqno = integer.parseint (In. Readline) based on accepted user numbers and friends numbers ()); System.out.println (FriendicQno); Int myicqno = integer.parseint (in.readline ()); system.out.println (myicqno); string addfriend = "delete from friend where icqno =? And friends = ? "; PreparedStatement prepare7 = c7.prepareCall (addfriend); prepare7.clearParameters (); prepare7.setInt (1, myicqno); prepare7.setInt (2, friendicqno); int r7 = 0; r7 = prepare7.executeUpdate (); IF (r7 == 1) System.out.Println ("OK Delfrien"); // Successfully else system.out.println ("false Delfriend"); // failed} catch (Exception E) {E.PrintStackTrace () System.out.println ("del false");}}} // end delete friend // Execute User Delete Friends End // The following handle user exit program else if (str.equals ("logout")) {Try {Class .forname ("Sun.jdbc.odbc.jdbCodbcdriver"); Connection C8 = DriverManager.getConnection ("JDBC: ODBC: J AVAICQ ",", ""); // Connect the database, set its status field to 0, and the IP address is set to empty int myicqno = integer.parseint (in.readline ()); system .out.println; string status = "Update ICQ set status = 0, IP = '' WHERE ICQNO =?"; pretedStatement Prest8 = c8.prepareCall (status); Prest8.clearparameters (); Prest8.setint (1 , myicqno; int R8 = preSt8.executeUpdate (); if (r8 == 1) System.out.println ("Ok Logout"

Else System.Out.println ("false logout");} catch (Exception E) {E.PrintStackTrace (); System.out.Println ("Logout False");}} // logout end // Handling users End // Get Who Add me as Friend // The following handles those people add me as a friend so that I will notify them else if (Str.Equals ("getWhoaddme") {system.out.println ("getWhoaddme") Try {class.forname ("Sun.jdbc.odbc.jdbCodbcdriver"); Connection C9 = DriverManager.getConnection ("JDBC: ODBC: Javaicq", "," "); // Connect the database, according to my number, choose from a friend who added my table int myicqno = Integer.parseInt (in.readLine ()); System.out.println (myicqno); String getwhoaddme = "select icqno from friend where friend =?"; PreparedStatement prepare6 = c9 .preparecall; prepare6.clearparameters (); prepare6.setint (1, myicqn); ResultSet r6 = prepare6.executeQuery (); Vector who = new vector (); while (r6.next ()) {who.add ()) {who.add (NEW INTEGER (R6.Getint (1)));} // end while // then tell these friends' IP addresses, then send to users to tell other customers I have online for I. INT I = 0; I

}}} // End Get Who Add ME as Friend // Processing Overline System.out.Println ("Echo Ing:" Str);} System.out.Println ("Close ...");} catch (IOException e) {} // captured or exception finally {Try {socket.close ();} catch (ooException e) {}}}} public class server}}} public class server}}} public class server}}} public class server}}} public class server}}} public class server}}} public class server}}} PUBLIC CLASS Server}}} PUBLIC Static Void Main (String Args []) THROWS IOEXCEPTION {ServerSocket S = New ServerSocket (8080); // Create a socket system.out.println at the 8080 port ("Server Start .." s); try {whele (true) {socket socket = S.Accept () ; // Unlimited monitoring customer request system.out.println ("Connectino Accept:" Socket; try {new serverthread (socket); // Create a new thread} catch (ioException e) {socket.close (); }} Finally {s.close ();} // Capture or exception}} // server program ends the client program (part)

Customers establish a connection with the server via Socket (inetaddress, port). All servers and customers are built by constructing BufferedReader, PrintWrit, and then the two sides pass the input and output streams to pass the information, once the client's connection request is received, the server accept () method returns a newly built socket object. The client sends a message to the server, such as registration, login, find friend, etc. After the server receives the request from the customer, the request is requested for different messaging requests, although UDP is unreliable but is not important for ICQ reliability, and UDP is fast , The customer sends information through UDP. When the user logs in, the UDP creates UDP through class DataGrampacket and DataGramsocket includes its local accept port and send port, the default port is 5000 and 5001, send messages to your friends by the IP address of the friend, and accept messages (Receive (DataGrampacket) )). When the user receives the message via the UDP, the other party's IP address can be obtained through the DataGrampacket method (). By comparing the friend list, the user is determined and prompting the user to receive a certain message, and then the user selects it The user views the message. If the friend does not have a message to receive a stranger. Users can view the message by strange buttons. User registration. When the server receives the user's registration request, the customer will start accepting the information, such as Customers, gender, gender, avatar, personal information, etc. After accepting, then connect to the background database, then add a record to the database, if successful, then return to its JICQ number, and register in the database The user's IP address, then updates its status to 1 user online. When the customer receives the information returned by the server, open the main program window and start to create a UDP to create a contact between users. ****** The procedure is as follows:

void jButton1_mouseClicked (MouseEvent e) {try {Socket socket = new Socket (InetAddress.getByName (sername), serverport); // server connected BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ())); PrintWriter out = new PrintWriter (new buffutstreamwriter (socket.getstreamwriter)), true); out.println ("new"); // Tell the server I want to register out.println (Nickname.getText (). Trim ()); // Tell the server my name, password, email, data out.println (password.getpassword ()); // and header number information OUT.PRINTLN (Email.getText (). Trim ()); Out.Println (Info.getText (). Trim ()); out.println (place.getSelectedItem ()); out.println (headpic.getSelected "; // Head picindex int no; no = integer.parseint (in.readline ()); //System.out.print (String str = ""; str = in.readline (). Trim (); // From the server get the status IF (Str.Equals ("false")) JOPTIONPANE.SHOWMESSAGEDIALOG (this, "Sorry, error: - (", "ok", joptionpane.information_message); // Failure Warning Else {// Successfully Open the main program JOPTIO Npane.showMessageDialog (this, "Your Javaicq # IS" NO, "OK", JOPANE.INFORMATION_MESSAGE); this.dispose (); mainwin f2 = new mainwin (no, sername, serverport); f2.setvisible (TRUE); } //System.out.println ("/n "); // }While (!")); // socket.close ();} catch (ooException E1) {}}} log in. On the client, the user enters its JICQ number and password, then establishes the connection with the server, tell the server I want to log in, after receiving, start reading the database through the JDBCODBC, then compare the information entered, if the same is to customers Returns success message and set its status field to 1 to indicate the online and register its IP address, otherwise returns an error. If the customer receives the successful information, open the main window, otherwise prompt error.

If successful, open the main program window and start create a UDP at the same time to create a connection between the user. The client then requests a list of friends to the server, the server receives the request, start reading the Friend table in the database, getting a friend's number, then read the friend information in the ICQ table, then send this information to the client, customer After receiving, you will show friends in the main window, such as avatar, namely. And create a number of vector (vector) to store friends, JICQ number, avatar number, IP address, etc. Some procedures are as follows: (the program flow chart is almost the same, slightly)

void login_mouseClicked (MouseEvent e) {try {Socket socket = new Socket (InetAddress.getByName (server), serport); // server connected BufferedReader in = new BufferedReader (new InputStreamReader (socket.getInputStream ())); // Create // Enter the stream printwriter out = new putterwriter (new buffoutwriter (socket.getstreamwriter ())), true); // creates output stream Out.println ("login"); // Tell the server I want to log in to OUT. Println (jicq.gettext ()); // Tell the server my number out.println (password.getpassword ()); // tell the server my password string str = ""; // do {str = in.readline ) .trim (); // get the message IF sent by the server (str.equals ("false")) JOPTIONPANE.SHOWMESSAGEDIALOG (this, "Sorry, error :-(", "ok", joptionpane.information_message; // Failed else {this.dispose (); int g = integer.parseint (jicq.gettext ()); mainwin f2 = new mainwin (g, server, server); // If success, open the main program F2.SetVisible. True);} //system.out.println ("/n "); // }while (!");} catch (ooexcept ION E1) {}}

Users add friends. After the customer logs in, then after the search button, start to send a lookup request to the server, the server reads the database table ICQ and returns the result to the customer, and the customer is received in the Find window. If the user selects a friend, send it to the server. Add a friend request, add your own number as well as your own number and the number of your friends after receiving the database, and read its basic information from the ICQ table to return to the client, and then the customer receives and displays the friend. And inform the customer via UDP, after receiving the message, you can choose to add the user as a friend or not. (Procedure Flow Chart and Program, Word Source Program) User Deletes Friends. The user selects the friend you want to delete in its friends and press the deletion, then send a delete request to the server, after receiving the request, connect the database table Friend to delete the user and the friend's record, if success, return to the customer to success message, After receiving the customer, delete the friend in its friend list. (Procedure Flow Chart and Program, VOV) User Sends and receives messages. The user communicates information with other users through the UDP through the IP address of the friends in the friend list, (the program flow chart and program, "see the source program Src.zip) and some program run results interface diagram Pic.zip III. The program interface program interface mainly refers to Tengxun's QQ2000, and the Java's SWING graphics package used in the implementation. The development tool is used by Borland's JBuilder4.

four. The program source program see Src.zip. Some program run results interface diagram PIC.zip. Server: (Windows Platform) First, there should be Java Environment JDK, which is recommended to use JDK1.3. Then there should be a database system to create a database Javaicq, and set table ICQ and table Friend. Then set the data source Javaicq to establish a connection to the database in the ODBC data source in the control panel. Then run Javac Server.java, Java Server, and can. Client: JDK1.3 can be suggested as long as there is a Java environment JDK. Then run Javac New.java, Java New, and can.

Fives. Reference: Java2 Graphic Design Volume 2: Swing (US) David M.GEary Java2 Programming Thought (US) Bruce Eckel Unix Network Programming (Volume 1) (US) W.Richard Stevens

In addition, the program selects a fixed port on the port, so it can only be run once in the same machine, if the single-machine debug can modify the UDP port of the client (my 5000 directory is an example, will int name, int sendport = 5000 Change to int UDPPORT = 5000, int successport = 5001) What is the last thing, listen to the decomposition .....

转载请注明原文地址:https://www.9cbs.com/read-110178.html

New Post(0)