Shake screen and send and receive various types of files

Source: Internet
Author: User
Tags sendfile

Shake screen and send and receive various types of files

1. Preface

This is the third article in this series, the last one we talked about the implementation of a client-to-client of the ordinary chat, this article to achieve a friend to send chatter screen and sending and receiving various types of files, I have different messages encapsulated, and the server parsing messages are reconstructed. As usual I will deploy the chat server to the WAN server, then you can open the source inside the client to chat with me! (This is just a junior version of the feature is simple does not support offline messaging, so the premise of chatting is I am online (the user named Zhang San is me, q me) ... ), you can also open two client tests, the server deployment document is placed in the root directory of my source code.

2. This article realizes the function

1. Sending and receiving chattering messages between clients.

2. Sending and receiving files between clients.

3. Concrete implementation

(1) enumeration of message types

Message type

1 public enum Msgtypeenum 2   {3      //  Login message 4      login =0, 5      //General message 6      String =1, 7      //jitter screen 8      Sh ake=2, 9      //File      file=311   }

(2) Message class

A variety of custom protocols for different messages; (login messages are only used when connecting to the server, so no message classes are written)

A. Custom protocol for generic messages ("|" This symbol is the system resolution sign)

If we assume that the current user is Zhang San, send a "hello" to your friend Li Shifa. The format for sending to the server through the socket is "1 three | john Doe | Hello", then sent to the John Doe client through the server's resolution, (you may have the question why the message is forwarded by the server resolution, why not the client sends the message directly to the client, so it is more convenient, In fact, if you deploy and WAN, the client through the socket is not directly connected to the friend client, must be deployed on the WAN server to ensure communication between them)

B. Custom protocol for chattering ("|" This symbol is the system resolution sign)

If we assume that the current user is Zhang San, send a flick message to a friend John Doe, the format for sending to the server via the socket is "2 three | John Doe |" and then sent to the John Doe client through the resolution of the server, John Doe the client calls its own Jitter method.

C. Custom protocol for files ("|" This symbol is the system resolution sign)

If we assume that the current user is Zhang San, send a TXT file to the friend John Doe, the format for sending to the server via the socket is "3 three | John Doe |". txt| file stream, and then through the resolution of the server sent to the John Doe client, John Doe client determines whether to save the file (this is just to implement directly read the file, only for small files (read to the default 5M in memory), large files to use the breakpoint to continue the transfer of technology, do not do research here.

<summary>
Message class
</summary>
public class Mymessage
{
Msgtypeenum Msgtype;
String FilePath;
String strMsg;
<summary>
Plain text messages
</summary>
<param name= "msgstring" > Messages </param>
Public Mymessage (String msgstring)
{
This.msgtype = msgtypeenum.string;
This.strmsg = msgstring;
}
<summary>
Message type
</summary>
<param name= "Msgtype" ></param>
Public Mymessage (Msgtypeenum msgtype)
{
This.msgtype = Msgtype;
}
<summary>
File type
</summary>
<param name= "FilePath" ></param>
<param name= "Msgtype" ></param>
Public Mymessage (String filePath, Msgtypeenum msgtype)
{
This.msgtype = Msgtypeenum.file;
This.filepath = FilePath;
}
<summary>
Returns a message based on message type byte array
</summary>
<returns></returns>
Public byte[] Tobytedata ()
{
Message array
byte[] arrmsg = null;
Switch (msgtype)
{
Case msgtypeenum.string:
{
1. Turning the message string into a byte array
Arrmsg = System.Text.Encoding.UTF8.GetBytes (STRMSG);
Break
}
Case Msgtypeenum.file:
{
String fileType = Path.getextension (filePath) + "|"; The type of file you are prompted to receive
byte[] Buffer0 = Encoding.UTF8.GetBytes (FileType);
var list = new list<byte> ();
List. AddRange (BUFFER0);
Here directly read the file, only suitable for small files (read into memory), large files to use the breakpoint to continue the transmission of technology
List. AddRange (File.readallbytes (FilePath));
byte[] Newbuffer = list. ToArray ();
Arrmsg= Newbuffer;
Break
}
Case Msgtypeenum.shake:
{
Arrmsg = new Byte[0];
Break
}
}
return arrmsg;
}

<summary>
Flag Message Type + Sender + Recipient (Final message)
</summary>
<param name= "Oldarr" ></param>
<param name= "Fromclient" ></param>
<param name= "Toclient" ></param>
<returns></returns>
Public byte[] Makenewarrwithflag (byte[] oldarr,string fromclient,string toclient)
{
Message format: (type identifier) sender | Recipient + Specific Information
String str = fromclient + "|" + toclient + "|";
byte[] Buffer0 = Encoding.UTF8.GetBytes (str);
var list = new list<byte> ();
List. AddRange (BUFFER0);
List. AddRange (Oldarr);
byte[] Newbuffer = list. ToArray ();
byte[] NewArr = new Byte[newbuffer. Length + 1];
1. Convert the type of the current object to the first element of the new array with an identifying value
Newarr[0] = (byte) msgtype;
2. Copy the data from the old array into the new array (starting from the second position of the newly array)
Newbuffer. CopyTo (NEWARR, 1);
3. Return an array of new messages with identity bits
return NEWARR;
}
}


(3) Sending of messages

Take file sending as an example

A. Selecting a file

1 private void Btnselfile_click (object sender, EventArgs e) 2       {3           using (OpenFileDialog ofd = new OpenFileDialog () ) 4           {5               ofd. MultiSelect = false; 6               ofd. Title = "Select the file to send"; 7               if (OFD. ShowDialog () = = DialogResult.OK) 8               {9                   FilePath = ofd. filename;10                   txtmsg.text = filepath;11               }12           }13       }

B. Sending files

1 private void Btnsendfile_click (object sender, EventArgs e) 2 {3 if (! Isselectfriend () | |           filepath== "") 4 {5 MessageBox.Show ("Select Friends and Files"); 6 return; 7} 8 Friend = LbFriends.SelectedItem.ToString (); 9 Try10 {11//interface Display message string newstr = "I" + ":" + friend + "\ r \ n" + "\" Send A file \ "" + "____[" + DateTime.Now +13 "]" + "\ r \ n" + "\ r \ n";               Smsg (NEWSTR); SendFile (); filePath = "";}18 catch19 {20 MessageBox.Show ("Connection to Server failed"),}22}23 private void SendFile () 25 {26//Message Class Create-the message format sent to the server is (Sender | recipient | information) mymessage msg = new Mymessage (filepath,msgtypeenum.file); 28//Message to Byte byte[] buffer = Msg. Tobytedata (); 30//Add identifier + Sender | Recipient |31 byte[] Sendbuffer = Msg. MakeneWarrwithflag (buffer, userName, friend), Clientsocket.send (sendbuffer); txtmsg.text = ""; 34}

(4) Receipt of messages

Take a screenshot message to receive as an example

A. Judging message types

New message Flag bit resolution in the receive thread method of the listener service socket

1 public void Recemsg () 2 {3 while (true) 4 {5 try 6 {7 var Buffer = new BYTE[1024*1024*5]; 8 9 int datelength = clientsocket.receive (buffer); Receive the data sent over the server 10//general message one by one if (buffer[0] = = (byte) msgtypeenum.string) 12 {1                     3//Do not parse the first bit identifier handlestr (buffer, datelength); 15}16                     Shake Screen Message-else if (buffer[0] = = (byte) msgtypeenum.shake) 18 {19 Handleshake (buffer, datelength); 20}21//File message on the other if (buffer[0] = = (byte)                 Msgtypeenum.file) handlefile (buffer, datelength), 25}26             Else27 {MessageBox.Show ("failed to receive file parsing"); 29}30}31   Catch32 {33          }34}35}36 PNs public void Handleshake (byte[] buffer, int datelength) 38 {39//Do not resolve the first bit identifier 40 String receivemsg = Encoding.UTF8.GetString (buffer, 1, dateLength-1); string[] MsgTxt = Receivemsg.split (' | ');                        Newstr string = "" + msgtxt[0] + ": I" + "\ r \ n" + "+" \ "sent a dithered screen \" "+" ____["+43 DateTime.Now + "]" + "\ r \ n" + "\ r \ n"; 44//The received message is displayed in a text box.  Showsmsg (NEWSTR), 46//Vibration shakebody (); 48}

B. Parsing the screen-shaking effect

1   Random randobj = new Random (), 2  3 private void Shakebody () 4         {5             //1. Get form Current coordinates 6 point             oldpoint = th Is. Location; 7             //2. Cycle change Form coordinates 8             for (int i = 0; i < i++) 9             {                 //3. Set new random coordinates one by one                 . Location = new Point (Oldpoint.x + randobj.next (+), Oldpoint.y + Randobj.next ());                 System.Threading.Thread.Sleep (//4);                 restore coordinates.                 Location = oldpoint;15                 System.Threading.Thread.Sleep (a);             }17         }

(5) Message presentation

A. Shaking screen effect

B. Document sending and receiving effect

(6) Summary

This time realizes the client's chattering screen and sending and receiving various types of files. The implementation of the idea is generally: Client 1 uses a custom protocol to send different types of messages to the server and then by the server resolution forwarded to the client 2. Okay, the basic principle of chatting is almost finished here. These are just the user's simulations, the next one we join the SQL Server database to implement login and friends add and other functions. Finally you can open the source code of the client, login Zhang San other than the client to send me a message, I am logged on this side of the Zhang San account, or open two clients to chat (do not need to run the server, the default is my servers IP, theoretically have a network can chat), quickly try it!!!

This series has not been finished and is to be continued ........ , looking forward to your attention

Source Address: Http://pan.baidu.com/s/1nvs3JmT

Shake screen and send and receive various types of files

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.