Network Programming Instant messaging Program (chat room)------(iii) client login __ Programming

Source: Internet
Author: User

In the previous section we talked about the service-side set-up of the instant messaging program, and today we are implementing the client login.

Just like we QQ login need a unique QQ number, of course, the QQ number is used for a long time, and our real-time communication program is only temporary chat use, in order to distinguish different users, we need users to use the program to register a username, and then to the fixed ip+ port to send a request to connect to the server. First the last picture, and then start the explanation.

The above has said, in the log in need of users to start a user name, this user name of course can be free to start, and then login, connect to the server, this time need server attention is the name of the username problem, we still remember when we set up the server side of a dictionary< String,socket> dictionary onlinelistserver to save the socket responsible for communication with the client, that is, the dictionary key is unique, so this username must be unique, the user is random input, of course, there may be duplicate problems, If there is a duplicate name, this time we need to do double processing on the server side and the login end, in the service side, we have already said, after the user connection succeeds to determine whether the Onlinelistserver dictionary has the same key as the user name, and if it exists, the username + "1", and add the communication socket that is responsible to the dictionary. and to the login to send a message to tell the login end, the user name already exists, to the client to do duplicate processing, client-side to accept the message sent by the server, according to the different content of the message to do different processing, if the duplicate name, and the client will be the same username + "1 If the name is not the same, the direct login is successful and the client main interface is performed.

Below I will pass the concrete code to explain slowly with everybody.

First create a form, named Clientlogin, where the interface is laid out, the main controls are as follows:

Three text boxes, respectively Txtip,txtport,txtname, representing the requesting server IP and port, login username

Two buttons for BTNDL,BTNQX, respectively, for login and cancellation.

Because we need to record the login name, and then according to different logins to distinguish between different users, and each login corresponding to a corresponding TcpClient object to connect, listen to the client and communicate with other objects. So we need to add additional attributes for the Clientlogin are string type LoginName and TcpClient type TcpClient, respectively, representing the user login name and the TcpClient instance responsible for connection traffic.

The code is as follows:

In public partial class Clientlogin:form

{} Add attribute:

public string loginname//logon name        
{            
        Get Set
}
Public TcpClient tcpclient//Connection Communication instance        
{            
        Get Set        
}

Write the following code in the handling function of the Click event of the Btndl button
private void Btndl_click (object sender, EventArgs e)        
{            
if (!string. IsNullOrEmpty (txtIP.Text.ToString ())//To determine whether the IP is null, request, listen to server IP            
{                
if (!string. IsNullOrEmpty (TxtName.Text.Trim ())//To determine whether the user name is empty, request a service-side fixed port                
{                    
This. LoginName = txtName.Text;                    
Try                    
{                        
This. TcpClient = new TcpClient ();//Sample Clientlogin.tcpclient Property                        
This. Tcpclient.connect (Ipaddress.parse (Txtip.text), Convert.ToInt32 (Txtport.text));//Connect server                        
NetStream = Tcpclient.getstream ();                        
byte[] buffer = Encoding.Default.GetBytes ("on|" + LoginName + "|");                        
Netstream.write (Buffer,0,buffer. LENGTH);//Send the login name to the server and wait for authentication on the service side                        
Thread.Sleep (100);                    
Byte[] Buffer1=new byte[1];                    
Netstream.read (buffer1, 0, 1);//Get Authentication messages for service-side postbacks                    
String i = Encoding.Default.GetString (buffer1);//do different processing according to different messages                    
if (i== "1")//if "1" means the name of the username, you need to do the duplicate                    
{                        
This. LoginName + = "1";                    
}                        
This. DialogResult = DialogResult.OK;                           
This. Close ();                    
}                    
catch (Exception E1)                    
{                        
MessageBox.Show ("Connection exception:" + E1.) message);                    
}                
}                
Else                
{                    
MessageBox.Show ("Please enter a login nickname.") ");                
}            
}            
Else            
{                
MessageBox.Show ("Make sure to enter a valid IP address.) ");            
}        
}

Do the following in the Cancel button:

private void Btntc_click (object sender, EventArgs e)        
{            
This. DialogResult = dialogresult.no;            
This. Close ();        
}

This time the login for the Instant messaging program has been done, but now please consider such a problem, our login interface is only a login connection role, in the successful login after we entered the chat interface, the login interface does not make any sense, how the login interface to eliminate, Some would say direct this. Isvisialbe=fales, Hidden, but in this case, even after the chat client is closed, the program is still running because the main program is not closed. Maybe some friends will say, direct this.close (), but in this case the entire application is closed, because the main program that we enable in Program.cs is the Clientlogin interface, the interface closes, the program is closed. So how do we do that?

This time we need to make the following modifications in the Program.cs file:

static void Main ()        
{            
Application.enablevisualstyles ();            
Application.setcompatibletextrenderingdefault (FALSE);            
Clientlogin clientlogin = new Clientlogin ();            
if (clientlogin.showdialog () = = DialogResult.OK)            
{                
Application.Run (New ChatClient (Clientlogin));            
}            
Else            
{                
Application.exit ();            
}        
}

In the main function of the application, we first instantiate a Clientlogin object, that is, when the program runs, the login page pops up, and then the result of the landing Interface Clientlogin.showdialog () is judged, If the landing success is: DialogResult.OK This time the program began to run chat main client, if DialogResult is not OK, then the chat master client will not run at all. Now we understand why there are four lines of code in the ClientLogin.cs page to highlight the bar, they are to give Clientlogin DialogResult property assignment, according to the different login situation, assign different values, and then control the chat main client whether run. Here if we shut down the chat main client, our program will shut down immediately, because the main program that we run is the chat main client, not the login end. If you don't understand this, you can see my previous blog. C # Closes the login form, after entering the main form, the main form closes, and the program process is still running.

OK, this section is here, in this section we implemented the Instant Messenger client login, where we need to pay attention to the client log on the same name problem, and login successfully after the login form shutdown problem. Hope that we can help, but also hope that everyone a lot of guidance. I'll give you the next section to teach you how to implement an Instant messaging program for the main client, which is the chat piece.

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.