asp.net use socket to achieve a simple multi-chat room source

Source: Internet
Author: User

Because in the transmission of the server and the client only byte stream to complete the transmission of data, then we can add a flag in different numbers.

The graph is the HTTP message captured by HttpWatch
This source of thought originates from HTTP request and response messages, simulates HTTP requests and responses, I specify the first byte in the stream of bytes {0: text, 1: file, 2: Shake}.
But at this time there is a disadvantage, if the logo will add a function, such as requiring users may control different text size, different text and color. So the signs are more and more, the transmission of the message is increasingly difficult to encapsulate and parse (the middle of a number of definitions, merging and unpacking the string process).
This time we will use the image of the object of thought to think about this problem. Can you use an object for transmission? Because the network is in a byte array in the form of transmission in different computers, then how to convert an object into a byte array in different computers to send it?
This time we should think of serialization.
Figure for my file structure
Because my server and client are in different assemblies, I define a common class library to be transferred in different assemblies.





The code is as follows Copy Code
Mycommon class:
[Serializable]


public class Mycommon


{


Defining flags


private int flag;


public int Flag


{


get {return flag;}


set {flag = value;}


}


Array of bytes Transferred


Private byte[] buffer;


Public byte[] Buffer


{


get {return buffer;}


set {buffer = value;}


}


}
Server side:
The code is as follows Copy Code
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using System.Net;
Using System.Net.Sockets;
Using System.Threading;
Using System.IO;
Using System.Runtime.Serialization.Formatters.Binary;


Namespace Mychatserver


{


public partial class Form1:form


{


Public Form1 ()


{


InitializeComponent ();


Do not detect the legality of cross-threading operations


Control.checkforillegalcrossthreadcalls = false;


}


When multiple users connect to the same server, record communication points and correspondence socket, with the dictionary key value pair to save, convenient to call, so that the server can choose to send messages to different users


dictionary<string, socket> dicsocket = new dictionary<string, socket> ();


dictionary<string, thread> dicthread = new dictionary<string, thread> ();
        private void Btnstart_click_1 (object sender, EventArgs e)
 & nbsp;      {
           // IP address
            ipaddress IP = ipaddress.parse ( Txtserver.text);
           //any available IP address on the current computer
            //ipaddress IP = ipaddress.any;
            IPEndPoint point = new IPEndPoint (IP, int. Parse (Txtport.text));
           //create socket for listening
             SOCKET socket = new Socket (AddressFamily.InterNetwork, SocketType.Stream, PROTOCOLTYPE.TCP);
            Try
             {
                //Binding IP and port number
                 socket. Bind (point);
               //Listening
                 socket. Listen (10);
ShowMsg ("Start listening");
}
catch (Exception ex)
{
ShowMsg (ex. message);
Return
}
Thread th = new Thread (Listen);


Th. IsBackground = true;


Th. Start (socket);


}





int count = 0;


void Listen (Object o)


{


Socket socket = o as socket;


while (count<100)


{


Try


{


count++;


Create a socket that is responsible for communication blocking the operation of the form


Socket Connsocket = socket. Accept ();





string s = connSocket.RemoteEndPoint.ToString ();


ShowMsg (S + ": Connection Success");


To record the socket used for communication


Dicsocket.add (S, connsocket);


CBOUSERS.ITEMS.ADD (s);
                    //Receive Message
                     thread th = new Thread (RECMSG);
                     th. IsBackground = true;
                     th. Start (Connsocket);
                     Dicthread.add (s, th);
               }
                catch (Exception Ex)
                {
                     ShowMsg (ex. message);
                     break;
               }
           }
       }
void Recmsg (Object o)


{


Socket connsocket = o as Socket;


while (true)


{


Try


{


Receive messages sent by client


byte[] buffer = new byte[1024 * 1024];


Number of actual valid bytes received by num


int num = connsocket.receive (buffer);


string s = Encoding.UTF8.GetString (buffer, 0, num);


ShowMsg (connSocket.RemoteEndPoint.ToString () + ":" + s);


}


catch (Exception ex)


{


ShowMsg (ex. message);


Break


}


}


}


void ShowMsg (String msg)


{


Txtlog.appendtext (msg + "RN");


}
Server sends messages


private void Btnsend_click (object sender, EventArgs e)


{


Gets the text box contents into a byte array


byte[] buffer = Encoding.UTF8.GetBytes (Txtmsg.text);


Try


{


list<byte> list = new list<byte> ();


Sign 0 text


List. ADD (0);


List. AddRange (buffer);


Common.mycommon my = new Common.mycommon ();


My. Flag = 0;


My. buffer = buffer;
Sockets for communication with the client


Gets the IP address of the currently selected client


string s = cbousers.text;


Dicsocket[s]. Send (Serialize (my));


}


catch (Exception ex)


{


ShowMsg (ex. message);


}


}


private void Form1_Load (object sender, EventArgs e)


{


}


Select File


private void Btnselect_click (object sender, EventArgs e)


{


OpenFileDialog ofd = new OpenFileDialog ();


if (OFD. ShowDialog () = = System.Windows.Forms.DialogResult.OK)


{


Txtpath.text = ofd. FileName;


}


}
       //Send file
        private void Btnsendfile_click (object sender, EventArgs e)
        {
             string key = Cbousers.text;
            using (FileStream fs = new FileStream ( Txtpath.text,filemode.open)
            {
 & nbsp;              byte[] buffer = new BYTE[FS. Length];
                FS. Read (Buffer,0,buffer. Length);
list<byte> list = new list<byte> ();
Sign 1 file
List. ADD (1);
List. AddRange (buffer);
Common.mycommon my = new Common.mycommon ();
My. Flag = 1;
My. buffer = buffer;
                Dicsocket[key]. Send (Serialize (my));
           }
       }
       //vibration
        private void Btnzd_click (object sender, EventArgs e)
        {
             string key = Cbousers.text;
byte[] buffer = new BYTE[1];
Sign Vibration
Buffer[0] = 2;
Common.mycommon my = new Common.mycommon ();
My. Flag = 2;
Dicsocket[key]. Send (Serialize (my));
}
serialization, I want to convert this object into an array, and then I'm going to get the object back to the array.


Byte[] Serialize (Common.mycommon my)


{


First convert this object into a stream, and then change the flow to a byte array, this stream is only a transit stream, with the memory stream can be


using (MemoryStream stream = new MemoryStream ())


{


BinaryFormatter bf = new BinaryFormatter ();


Bf. Serialize (stream,my);


To replace a serialized flow with an array.


byte[] buffer = stream. ToArray ();


Returns a byte array


return buffer;


}


}


}


}
Client:



The code is as follows Copy Code
Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Linq;
Using System.Text;
Using System.Windows.Forms;
Using System.Net;
Using System.Net.Sockets;
Using System.Threading;
Using System.IO;
Using System.Runtime.Serialization.Formatters.Binary;


Namespace Mychatclient


{


public partial class Form1:form


{


Public Form1 ()


{


InitializeComponent ();


Control.checkforillegalcrossthreadcalls = false;


}


Socket socket;


private void btnStart_Click (object sender, EventArgs e)


{


IP address and port of the server


IPAddress IP = ipaddress.parse (txtserver.text);


IPEndPoint point = new IPEndPoint (ip,int. Parse (Txtport.text));


Socket = new Socket (addressfamily.internetwork, SocketType.Stream, protocoltype.tcp);


Try


{


Connecting to a server


Socket. Connect (point);


ShowMsg ("connected successfully");
Messages sent by the receiving server


Thread th = new Thread (RECMSG);


Th. IsBackground = true;


Th. Start ();


}


catch (Exception ex)


{


ShowMsg (ex. message);


}


}


Message sent by the receiving server


void Recmsg ()


{


while (true)


{


Try


{


byte[] buffer = new byte[1024 * 1024];


int num = socket. Receive (buffer);
Common.mycommon my = deserialize (buffer, num);
When is the text


if (My. Flag = 0)


{


string s = Encoding.UTF8.GetString (My. Buffer, 0,my. Buffer.length);


ShowMsg (s);


}


Receiving files


else if (my. Flag = 1)


{


Prompts you to save the file


DialogResult dr = MessageBox.Show ("Do you want to save the file?") "," hint ", messageboxbuttons.yesno);


if (dr = = System.Windows.Forms.DialogResult.Yes)


{


SaveFileDialog sfd = new SaveFileDialog ();


Save file Win7 When using the note, you must add this


if (SFD. ShowDialog (This) = = System.Windows.Forms.DialogResult.OK)


{


using (FileStream fs = new FileStream (SFD). Filename,filemode.create))


{


Fs. Write (My. Buffer,0,my. Buffer.length);


}


}


}


}


else if (my. Flag = 2)


{


The window is placed at the top level


This. topmost = true;


Vibration


ZD ();


}


}


catch (Exception ex)


{


ShowMsg (ex. message);


Break


}


}


}
void ShowMsg (String msg)
{
Txtlog.appendtext (msg + "RN");
}
Send a message


private void Btnsend_click (object sender, EventArgs e)


{


if (socket!= null)


{


Try


{


byte[] buffer = Encoding.UTF8.GetBytes (Txtmsg.text);


Socket. Send (buffer);


}


catch (Exception ex)


{


ShowMsg (ex. message);


}


}


}
private void Form1_Load (object sender, EventArgs e)


{





}


Vibration


String dir = "Top";


int count = 10;


void ZD ()


{


for (int i = 0; i &lt; count; i++)


{


if (dir = = "Top")


{


dir = "Bottom";


This. Location = new Point (this. Location.x-5, this. LOCATION.Y-5);


}


Else


{


dir = "Top";


This. Location = new Point (this. Location.x + 5, this. LOCATION.Y + 5);


}


System.Threading.Thread.Sleep (50);


}
}
       //deserialization, converting a byte array to an object,
         Common.mycommon Deserialize (byte[] buffer,int num)
        {
             using (MemoryStream ms = new MemoryStream (buffer, 0, num) )
            {
                 BinaryFormatter bf = new BinaryFormatter ();
                Common.mycommon my = bf. Deserialize (MS) as Common.mycommon;
return to my;
}
}
}
}
Come on, let's see the results.

This is just an experiment, the client is only the server forwarding, if you want to do imaging QQ, can be combined with ado.net, in fact, the core is these, if you want to perfect, there are still a lot of questions to consider

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.