A simple chat program (Socket)

Source: Internet
Author: User



Service-Side server code:

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.io;using system.linq;using system.net;using system.net.sockets;using system.text;using System.Threading     Using system.threading.tasks;using system.windows.forms;namespace Socket Network programming _server{public partial class Form1:form        {public Form1 () {InitializeComponent (); } private void btnStart_Click (object sender, EventArgs e) {try {//when clicked When you start listening, create a socket socket Socketwatch = new socket (addressfamily.internetwork, sockettype) on the server side that is responsible for monitoring IP addresses and port numbers.                Stream, PROTOCOLTYPE.TCP);                IPAddress IP = ipaddress.any;                Create a port number object IPEndPoint point = new IPEndPoint (IP, Convert.ToInt32 (txtport.text));                Monitor Socketwatch.bind (point);                ShowMsg ("monitor success");               Socketwatch.listen (10); Thread th = new Thread (Listen); Th.                IsBackground = true; Th.            Start (Socketwatch);        } catch {}}///<summary>//wait for client connection and create socket for communication with        </summary> Socket Socketsend;            void Listen (Object o)//The function executed by the thread, if there is an argument, must be the Object type {socket socketwatch = O as socket; Wait for the client to connect and create a socket for communication while (true) {try {/                    /Socket socketsend = Socketwatch.accept () that is responsible for communicating with the client;                    The IP address and socket of the remote connected client are deposited into the collection Dicsocket.add (SocketSend.RemoteEndPoint.ToString (), socketsend);                    The IP address and socket of the remote connected client are deposited into the drop-down box CboUsers.Items.Add (socketSend.RemoteEndPoint.ToString ());                 192.168.11.87: Connection succeeded ShowMsg (socketSend.RemoteEndPoint.ToString () + ": Connection succeeded");   Open a new thread and receive the message from the client thread th = new Thread (Recive); Th.                    IsBackground = true; Th.                Start (Socketsend);        } Catch {}}}//Put the IP address and socket of the remote connected client into the collection        dictionary<string, socket> dicsocket = new dictionary<string, socket> (); <summary>//server-side receive messages from clients///</summary>//<param name= "O" &GT;&LT;/PARAM&G        T            void Recive (Object o) {socket socketsend = O as socket;                    while (true) {try {//Client connection succeeds, the server should accept the information sent by the client                    byte[] buffer = new BYTE[1024 * 1024 * 2];                    The actual number of valid bytes received int r = socketsend.receive (buffer);                    if (r = = 0) {break; } string str = Encoding.UTF8.GetString (buffer, 0, R);                ShowMsg (Socketsend.remoteendpoint + ":" + str); } Catch {}}} void ShowMsg (String str) {Txtlo        G.appendtext (str + "\ r \ n");  private void Form1_Load (object sender, EventArgs e) {control.checkforillegalcrossthreadcalls =        False }///<summary>//The server sends a message to the client///</summary>//<param name= "Sender" ><        /param>//<param name= "E" ></param> private void Btnsend_click (object sender, EventArgs e)                {try {string str = Txtmsg.text;                byte[] buffer = Encoding.UTF8.GetBytes (str);                list<byte> list = new list<byte> (); List.                ADD (0); List.                AddRange (buffer); Converts a generic collection to a collection byte[] Newbuffer = list. ToarrAy ();                Get the IP address of the user in the dropdown box always selected string IP = cboUsers.SelectedItem.ToString (); DICSOCKET[IP].                Send (Newbuffer);            Socketsend.send (buffer); } catch {}}///<summary>//Select the file to send/        </summary>//<param name= "sender" ></param>//<param name= "E" ></param> private void Btnselect_click (object sender, EventArgs e) {OpenFileDialog ofd = new OpenFileDialog            (); Ofd.            Title = "Please select"; Ofd.            InitialDirectory = @ "C:\Users\Administrator\Desktop"; Ofd.            Filter = "All Files |*.*"; Ofd.            ShowDialog (); Txtpath.text = ofd.        FileName; private void Btnsendfile_click (object sender, EventArgs e) {//Get the path of the file to be sent by string pat            h = txtpath.text; using (FileStream fsread=new FileStream (path,filemode.open,fileaccesS.read) {byte[] buffer = new BYTE[1024 * 1024 * 5]; int r = fsread.read (buffer, 0, buffer.                Length);                list<byte> list = new list<byte> (); List.                ADD (1); List.                AddRange (buffer); byte[] Newbuffer = list.                ToArray (); Dicsocket[cbousers.selecteditem.tostring ()].            Send (newbuffer, 0, r+1, socketflags.none); }}///<summary>//Send vibration///</summary>//<param name= "Sender" &GT;&L        t;/param>//<param name= "E" ></param> private void Btnzd_click (object sender, EventArgs e)            {byte[] buffer = new BYTE[1];            Buffer[0] = 2; Dicsocket[cbousers.selecteditem.tostring ()].        Send (buffer); }    }}

Client-side code:

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.io;using system.linq;using system.net;using system.net.sockets;using system.text;using System.Threading     Using system.threading.tasks;using system.windows.forms;namespace Socket Network programming _client{public partial class Form1:form        {public Form1 () {InitializeComponent ();        } Socket Socketsend; private void btnStart_Click (object sender, EventArgs e) {try {//create Socke for communication T 1: Represents IP V4 2: What type of Stream, Stream 3: corresponding service socketsend = new Socket (AddressFamily.InterNetwork, Sockettype.st                Ream, PROTOCOLTYPE.TCP);                The IP address of the text box needs to be converted to the IPAddress type IPAddress IP = ipaddress.parse (txtserver.text);                The port number needs to be converted to the IPEndPoint type IPEndPoint point = new IPEndPoint (IP, Convert.ToInt32 (txtport.text)); Get the IP of the remote server application you want to connect toAddress and port number Socketsend.connect (point);                ShowMsg ("Connection succeeded");                A new thread is turned on to receive the message from the server side thread th = new Thread (Recive); Th.                IsBackground = true; Th.            Start (); } catch {}}///<summary>///non-stop receiving messages from the server///</summary> Voi D Recive () {while (true) {try {byte[] buf                    fer = new BYTE[1024 * 1024 * 3];                    The actual number of valid bytes received int r = socketsend.receive (buffer);                    if (r = = 0) {break;                        }//First to determine if the text message is sent if (buffer[0] = = 0) {                        Note that the decoding takes from the first start to the length-1 bytes of string s = Encoding.UTF8.GetString (buffer, 1, r-1); ShowMsg (Socketsend.remoteendpoint + ":" + s); } if (buffer[0] = = 1) {SaveFileDialog SFD = new savefiledial                        OG (); SfD.                        InitialDirectory = @ "C:\Users\Administrator\Desktop"; SfD.                        Title = "Please select the file to be saved"; SfD.                        Filter = "All Files |*.*"; SfD.                        ShowDialog (this);//Do not add this bounce? String path = sfd.                        FileName;                            using (FileStream fswrite=new FileStream (path,filemode.openorcreate,fileaccess.write)) {                        Fswrite.write (BUFFER,1,R-1);                    } MessageBox.Show ("Saved successfully");                    } if (buffer[0] = = 2) {ZD (); }} catch {}}}//<summary>//shake///<         /summary> void ZD () {   for (int i = 0; i <, i++) {this.                Location = new Point (200, 200); This.             Location = new Point (280,280);        }} void ShowMsg (String str) {Txtlog.appendtext (str + "\ r \ n"); }///<summary>//client sends a message to the server///</summary>//<param name= "Sender" ><        /param>//<param name= "E" ></param> private void Btnsend_click (object sender, EventArgs e)            {String str = TxtMsg.Text.Trim ();            byte[] buffer = Encoding.UTF8.GetBytes (str);        Socketsend.send (buffer);  private void Form1_Load (object sender, EventArgs e) {control.checkforillegalcrossthreadcalls =        False }    }}


A simple chat program (Socket)

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.