VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > C#教程 >
  • TCP/IP以及Socket聊天室带类库源码分享

TCP/IP以及Socket聊天室带类库源码分享

 

最近遇到个设备,需要去和客户的软件做一个网络通信交互,一般的我们的上位机都是作为客户端来和设备通信的,这次要作为服务端来监听客户端,在这个背景下,我查阅了一些大佬们的博客,和一些资料。将这些汇总做了一个简单的服务端监听和客户端的类库,希望对大家有一定的作用,当然更多还是给自己做一个日记。下面是类库和对类库测试的一些全部源代码。

1.通信类库

 

复制代码
using System;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace TCP_DLL
{
    public class PSS_Server
    {
        private Dictionary<string, Socket> cilentList = new Dictionary<string, Socket>();
        private Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        private Socket ConnCilent;
        /// <summary>
        /// 创建服务端
        /// </summary>
        /// <param name="ip">IP地址</param>
        /// <param name="Port">端口</param>
        public PSS_Server(string ip, int Port)
        {
            IPAddress _IP = IPAddress.Parse(ip);
            IPEndPoint endPoint = new IPEndPoint(_IP, Port);
            server.Bind(endPoint);
            server.Listen(20);
        }

        /// <summary>
        /// 接受客户端的连入请求
        /// </summary>
        /// <param name="retn"></param>
        /// <returns></returns>
        public bool Accept(ref string retn)
        {
            string info = "";
            try
            {
                ConnCilent = server.Accept();//接受一个连入的客户端
                if (ConnCilent != null)
                {
                    info = ConnCilent.RemoteEndPoint.ToString();
                    cilentList.Add(info, ConnCilent);
                    retn = info + "接入服务成功!";
                }
                return true;
            }
            catch (Exception)
            {
                retn = info + "接入服务失败!";
                return false;
            }
        }

        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public bool SendMsg(string str)
        {
            try
            {
                foreach (var item in cilentList)
                {
                    byte[] arrMsg = Encoding.UTF8.GetBytes(str);
                    item.Value.Send(arrMsg);
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 接收客户端消息
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool Receive(object obj, ref string msg)
        {
            Socket ConnCilent1 = ConnCilent;
            IPEndPoint endPoint = null;
            try
            {
                byte[] arrMsg = new byte[1024 * 1024];
                int Len = ConnCilent1.Receive(arrMsg);
                if (Len != 0)
                {
                    msg = Encoding.UTF8.GetString(arrMsg, 0, Len);
                    endPoint = ConnCilent1.RemoteEndPoint as IPEndPoint;
                }
                return true;
            }
            catch (Exception)
            {
                if (endPoint!=null)
                {
                    cilentList.Remove(endPoint.ToString());
                }
                return false;
            }
        }
        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Close()
        {
            try
            {
                server.Close();
                cilentList.Clear();
            }
            catch (Exception)
            {

            }
        }
    }

    public class PSS_Cilent
    {
        private Socket cilent = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
        /// <summary>
        /// 创建客户端
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="Port"></param>
        public bool Connect(string ip, int Port)
        {
            IPAddress _ip = IPAddress.Parse(ip);
            IPEndPoint endPoint = new IPEndPoint(_ip, Port);
            try
            {
                cilent.Connect(endPoint);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Close()
        {
            try
            {
                cilent.Close();
            }
            catch (Exception)
            {

            }
        }
        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public bool ReceiveMsg(ref string msg)
        {
            Socket _Cilent = cilent;
            try
            {
                //定义客户端收到的信息大小
                byte[] arrlist = new byte[1024 * 1024];
                //接收到的信息大小
                int Len = cilent.Receive(arrlist);
                msg = Encoding.UTF8.GetString(arrlist, 0, Len);
                return true;
            }
            catch (Exception)
            {
                _Cilent.Close();
                return false;
            }
        }
        /// <summary>
        /// 发送消息
        /// </summary>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool SenMsg(string msg)
        {
            try
            {
                byte[] arrmsg = Encoding.UTF8.GetBytes(msg);
                cilent.Send(arrmsg);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
}
复制代码

 

2.服务端源代码和界面

 

复制代码
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ServerTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private TCP_DLL.PSS_Server Server;
        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (Server.SendMsg(textBox3.Text).Equals(false))
                {
                    MessageBox.Show("发送消息失败!!");
                    return;
                }
                textBox3.Clear();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string retn = "";
            Server = new TCP_DLL.PSS_Server(textBox1.Text, int.Parse(textBox2.Text));
            textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + "创建服务完成,等待接入..." + "\r\n")));

            if (Server.Accept(ref retn).Equals(false))
            {
                MessageBox.Show(retn);
                return;
            }
            textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n")));


            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    string retn1 = "";
                    if (Server.Receive(ref retn).Equals(false))
                    {
                        MessageBox.Show("接收消息异常!!");
                        return;
                    }
                    textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n")));
                }
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Server.Close();
        }
    }
}
复制代码

2.客户端界面和源代码

 

复制代码
using System;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CilentTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private TCP_DLL.PSS_Cilent Cilent = new TCP_DLL.PSS_Cilent();

        private void textBox3_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode==Keys.Enter)
            {
                if (Cilent.SenMsg(textBox3.Text).Equals(false))
                {
                    MessageBox.Show("发送消息失败!!!");
                    return;
                }
                textBox3.Clear();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (Cilent.Connect(textBox1.Text,int.Parse(textBox2.Text)).Equals(false))
            {
                MessageBox.Show("连接失败!!!");
                return;
            }
            textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + "创建连接完成....." + "\r\n")));
            Task.Factory.StartNew(() =>
            {
                while (true)
                {
                    string retn = "";
                    if (Cilent.ReceiveMsg(ref retn).Equals(false))
                    {
                        MessageBox.Show("接收消息异常!!");
                        return;
                    }
                    textBox4.Invoke(new Action(() => textBox4.AppendText(DateTime.Now + "\r\n" + retn + "\r\n")));
                }
            });
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Cilent.Close();
        }
    }
}
复制代码

 3.效果图

 



 

出处:https://www.cnblogs.com/Tian-HW/p/15224125.html

相关教程