Summary of Socket-based simple chat tools (original) and socket chat tools

Source: Internet
Author: User

Summary of Socket-based simple chat tools (original) and socket chat tools

During this time, I can't help but try to write a summary to encourage myself to study hard and write poorly. Please advise me!

The following is a simple program for sending messages and files. First, the server needs to prepare two sockets and two threads as follows:

// Communicate with the client private Socket sckCommit; // listen to the Client private Socket sckListen; private Thread thdListen; private Thread thdCommit;

The listening and communication to the client are placed in two separate threads. The simple interface of the server is as follows:

Call the following function when you click the start button:

# Region initialize listener // initialize listener public void Listen () {try {string ip = txtIp. text. trim (); string port = txtPort. text. trim (); // create an IP address IPAddress ipaddress = IPAddress. parse (ip); // create an IP node IPEndPoint endpoint = new IPEndPoint (ipaddress, int. parse (port); // create a Socket sckListen = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // bind the IP node sckListen. bind (endpoint); sckListen. listen (10); // 10 is the maximum number of simultaneous connections // Listen to thdListen = new Thread (Watch); thdListen in a separate Thread. isBackground = true; thdListen. start (); ShowMsg ("server startup ................. ") ;}catch (Exception ex) {ShowErr (ex) ;}# endregion # region listens to the public void Watch () {while (true) port in a separate thread) {try {sckCommit = sckListen. accept (); thdCommit = new Thread (ReceiveMsg); thdCommit. isBackground = true; thdCommit. start (); ShowMsg ("Listening to connections");} catch (Exception ex) {ShowErr (ex); break ;}# endregion

Start the server to listen. When the program runs to sckCommit = sckListen. Accept ();, because of Accept ();, the running is blocked waiting for the client's connection, and then start the thread that receives the message.

public void ReceiveMsg()        {            while (true)            {                try                {                    byte[] b = new byte[1024 * 1024 * 4];                    int size = sckCommit.Receive(b);                    string msg = Encoding.UTF8.GetString(b, 0, size);                    ShowMsg(msg);                }                catch (Exception ex)                {                    ShowErr(ex);                    break;                }            }        }

For a client, you first need to actively connect to the server. The client is as follows:

When you click Connect, call the following function:

Public void Connnetion () {try {sckConnection = new Socket (AddressFamily. interNetwork, SocketType. stream, ProtocolType. tcp); // create an IP address IPAddress ipaddress = IPAddress. parse (txtIp. text. trim (); // create an IP node IPEndPoint endpoint = new IPEndPoint (ipaddress, int. parse (txtPort. text. trim (); // The Connection IP address is txtIp. text. trim () Port is txtPort. text. trim () sckConnection. connect (endpoint); thdConnection = new Thread (ReceiveMsg); thdConnection. isBackground = true; thdConnection. start () ;}catch (Exception ex) {ShowErr (ex) ;}} public void ReceiveMsg () {while (true) {try {byte [] byteMsg = new byte [1024*1024*4]; int length = sckConnection. receive (byteMsg); if (byteMsg [0] = 0) {string strMsg = Encoding. UTF8.GetString (byteMsg, 1, length-1); ShowMsg (strMsg);} else if (byteMsg [0] = 1) {// OpenFileDialog sfd = new OpenFileDialog (); // if (sfd. showDialog () = DialogResult. OK) // {// string savePath = sfd. fileName; using (FileStream fs = new FileStream (@ "1.txt", FileMode. create) {fs. write (byteMsg, 1, length-1); ShowMsg ("file saved successfully:") ;}/}} else {ShowMsg ("sdf ");}} catch (Exception ex) {ShowErr (ex); break ;}}}

In this way, we can accept the data sent from the server. To save space, other repetitive code will not be stuck.

 

It should also be noted that how to differentiate whether the sent data is a file or a message or a window jitters is to mark the first byte array to be sent,

If it is 0, how does one send a string? If it is 1, the file is sent. If it is 2, the window jitter is sent.

For the code above files and strings, the window jitter is not implemented yet. My idea is to use a for loop, which is 10-30 times. Each time x is generated with a random number, y and then add

On the current coordinates of the window, the window jitter can be realized.

 

Haha, now I want to summarize it. Now I am going to dinner and come back to make the window shake. Come on !!!!


Design flowchart and code based on socket chat tools

Too few points.
In the simplest way, the two clients establish a socket connection and then establish a persistent connection. When a message is sent, the client interprets the message and then displays the message. The message must be encapsulated and sent to the other party.

More complicated.
A socket server is then sent by the socket server to distribute messages. The socket server has many open-source servers. If you look at their documents, there will be no more arguments.

A small chat tool compiled using java Socket is successfully debugged on the local machine, but the two computers that can ping each other cannot be connected.

We recommend that you first use a simple program to test the client connection to the server, which can eliminate a lot of interference. The following two classes are the simplest code of the client and server. You should test them first, if the connection is still unavailable, send the exception information.
In addition, the Socket connection is prone to problems:
1) The server cannot be started due to a port conflict;
2) the IP address is incorrect. The IP address is divided into the local address, lan address, and Wan address. Test the IP address in different environments. If the IP address is incorrect, it cannot be accessed by the client, in addition, problems such as multiple NICs installed on the machine may cause errors;
3) The firewall prohibits Java programs from opening ports, not only the soft firewall of server machines, but also the LAN firewall may block external access.

Import java. io. IOException;
Import java.net. ServerSocket;
Import java.net. Socket;
Public class ServerMain {
Public ServerMain (){
Try {
ServerSocket ss = new ServerSocket (31647 );
Socket s = ss. accept ();
System. out. printf ("client connection successful: \ n % s \ n", s. toString ());
} Catch (IOException e ){
E. printStackTrace ();
}
}
Public static void main (String [] args ){
New ServerMain ();
}
}

Import java. io. IOException;
Import java.net. Socket;
Import java.net. UnknownHostException;
Public class ClientMain {
Public ClientMain (){
Try {
Socket s = new Socket ("192.168.1.100", 31647); // modify the IP address
System. out. println ("the server is connected successfully! ");
} Catch (UnknownHostException e ){
E. printStackTrace ();
} Catch (IOException e ){
E. printStackTrace ();
}
}
Public static void main (String [] args ){
New ClientMain ();
}
}

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.