net Winform socket 套接字聊天室客户端和服务端 源码

来源:互联网 发布:鬼武者系列 知乎 编辑:程序博客网 时间:2024/06/09 19:02

///-------------------------------------- 客户端----------------------------------

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;   // ipportend IPADRESS类  IPadress 端口和iP等信息using System.Net.Sockets;using System.Threading;using System.IO; namespace heima{    public partial class Form_Client : Form    {        public Form_Client()        {            InitializeComponent();        }        Socket sockeclient = null;   //创建负责监听的套接字        private void button1_Click(object sender, EventArgs e)        {            IPAddress adress = IPAddress.Parse(textBox1.Text);  //指定textbox1的text值为IPADDRESS 的 获取文本框的ip地址       // 创建包含ip和port的网络节点对象            IPEndPoint ippoint = new IPEndPoint(adress,int.Parse(textBox2.Text));              sockeclient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);  // 赋值负责监听的套接字 Socket方法中 寻址协议ip4  ,流的//协议,tcp协议 来监听            sockeclient.Connect(ippoint);  //l连接网络节点            ClienThre = new Thread(recemess);            ClienThre.IsBackground = true;            ClienThre.Start();                   }        void Show(string mess)        {            textBox3.AppendText(mess+"\r\n");        }        Thread ClienThre = null;        void recemess()        {            while (true)            {                byte[] merec = new byte[1024 * 1024];                string Strmerec = System.Text.Encoding.UTF8.GetString(merec, 0, sockeclient.Receive(merec)); //GetString方法从接受来的数组转成字符串                Show(Strmerec);            }                }        private void button2_Click(object sender, EventArgs e)  //发送事件        {            byte[] sendby = System.Text.Encoding.UTF8.GetBytes(textmegs.Text);            byte[] sentext = new byte[sendby.Length+1];            sentext[0] = 0;            Buffer.BlockCopy(sendby, 0, sentext, 1, sendby.Length);            sockeclient.Send(sentext);        }        private void button3_Click(object sender, EventArgs e)        {            if (openFiles.ShowDialog() != DialogResult.OK)            {            }else            {                textBox4.Text = openFiles.FileName;                        }        }        private void button4_Click(object sender, EventArgs e)//发送文件        {            using (FileStream fs = new FileStream(textBox4.Text, FileMode.Open))            {                byte[] Filebytesr = new byte[1024 * 1024 * 2];                int Length = fs.Read(Filebytesr, 0, Filebytesr.Length);//读到发送文件的的真实长度                byte[] Filete = new byte[Length+1];                Filete[0] = 1;                Buffer.BlockCopy(Filebytesr, 0, Filete, 1, Length);                sockeclient.Send(Filete);                Show(Filete[0].ToString());                                       }        }     }}

///-------------------------------------- 服务端----------------------------------

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; // ipportend IPADRESS类  IPadress 端口和iP等信息using System.Net.Sockets;using System.Threading;using System.IO;namespace heima{    public partial class Form_server : Form    {        public Form_server()        {            InitializeComponent();            TextBox.CheckForIllegalCrossThreadCalls = false;        }        private void Form_server_Load(object sender, EventArgs e)        {        }        Thread swchthread = null;        Socket swchsocket = null;        Socket sockconection = null;        void watchconect()        {               while (true)                {                      sockconection = swchsocket.Accept();//创建                    listBox1.Items.Add(sockconection.RemoteEndPoint.ToString());                    dic.Add(sockconection.RemoteEndPoint.ToString(), sockconection);                    showmge("连接成功!");                    Thread rec = new Thread(recemess);                    rec.IsBackground = true;                    rec.Start(sockconection);                    dicttread.Add(sockconection.RemoteEndPoint.ToString(), rec);                }                 }        void recemess(object sockets)        {            while (true)            {                Socket sockeclient = sockets as Socket;                byte[] merec = new byte[1024 * 1024];                try                {                    int Length = sockeclient.Receive(merec);                    if (merec[0] == 0)//是文件格式的                    {                        string Strmerec = System.Text.Encoding.UTF8.GetString(merec, 1, Length - 1); //GetString方法从接受来的数组转成字符串                        Console.Write(merec[0].ToString() + "文字输出------");                        Show(Strmerec);                    }                    if (merec[0] == 1)                    {                        SaveFileDialog Sfd = new SaveFileDialog();                        Console.Write(merec[0].ToString() + "wenjianshuchu");                        if (Sfd.ShowDialog() == DialogResult.OK)                        {                            string savepath = Sfd.FileName;                            using (FileStream fs = new FileStream(savepath, FileMode.Create))                            {                                fs.Write(merec, 1, Length - 1);                                showmge("文件保存成功" + savepath);                            }                        }                        else                        {                        }                    }                }                catch (SocketException ex)                {                    showmge("异常:" + ex.Message);                    dic.Remove(sockconection.RemoteEndPoint.ToString());                    dicttread.Remove(sockconection.RemoteEndPoint.ToString());                    listBox1.Items.Remove(sockconection.RemoteEndPoint.ToString());                    break;                }                catch (Exception ex) { MessageBox.Show(ex.Message); }            }        }              void Show(string mess)        {            textBox3.AppendText(mess + "\r\n");        }        private void button1_Click(object sender, EventArgs e)        {            //创服务端的负责监听的套接字的 参数  Ip4寻址协议, 流传输 TCp协议            swchsocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);            IPAddress ipadress = IPAddress.Parse(textBox1.Text);            IPEndPoint endport = new IPEndPoint(ipadress,int.Parse( textBox2.Text));             //把负责监听的套接字绑定到主机上            swchsocket.Bind(endport);            swchsocket.Listen(10); //同时支持10个在线            showmge("服务器启动成功!");            swchthread = new Thread(watchconect);            swchthread.IsBackground = true;            swchthread.Start();          }        void showmge(string mge)         {            textBox3.AppendText(mge+"\r\n");                } Dictionary<string,Socket> dic=new Dictionary<string,Socket>();//保存所有和服务器通信的套接字 Dictionary<string, Thread> dicttread = new Dictionary<string, Thread>(); //保存服务器所有通信的套接字接收线程        private void button2_Click(object sender, EventArgs e)        {            string messaa = textBox4.Text;            byte[] messbye = System.Text.Encoding.UTF8.GetBytes(messaa);            string stresend = listBox1.Text;            dic[stresend].Send(messbye);           // sockconection.Send(messbye);            showmge("发送成功!!"+messaa);        }        private void button3_Click(object sender, EventArgs e) //群发消息        {            string messaa = textBox4.Text;            byte[] messbye = System.Text.Encoding.UTF8.GetBytes(messaa);            foreach(Socket s in dic.Values)            {               s.Send(messbye);            }                                     // sockconection.Send(messbye);            showmge("发送成功!!" + messaa);        }    }}
转自:http://blog.csdn.net/szstephenzhou/article/details/7469420

0 0
原创粉丝点击