我是靠谱客的博主 怡然溪流,最近开发中收集的这篇文章主要介绍C#实现套接字发送接收数据,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

本文实例为大家分享了C#实现套接字发送接收数据的具体代码,供大家参考,具体内容如下

服务端

namespace TestServer
{
    public partial class ServerForm : Form
    {
        Socket socketSend;
        // 将远程连接的客户端的IP地址和socket存入集合
        Dictionary<string, Socket> dicSocket = new Dictionary<string, Socket>();
        public ServerForm()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                // 当点击开始监听后,在服务器创建一个负责监听IP地址和端口号的socket
                Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                IPAddress ip = IPAddress.Any;//;IPAddress.Parse(txtServer.Text)
                IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(txtPort.Text));
                // 监听
                socketWatch.Bind(point);
                ShowMsg("监听成功");
                socketWatch.Listen(10);
                Thread th = new Thread(Listen);
                th.IsBackground = true;
                th.Start(socketWatch);
            }
            catch { }
        }

        void Listen(object o)
        {
            // 等待客户端连接 并创建一个负责通信的Socket
            Socket socketWatch = o as Socket;
            while (true)
            {
                socketSend = socketWatch.Accept();
                dicSocket.Add(socketSend.RemoteEndPoint.ToString(),socketSend);
                cboUsers.Items.Add(socketSend.RemoteEndPoint.ToString());
                ShowMsg(socketSend.RemoteEndPoint.ToString() + " : " + "连接成功");
                Thread th = new Thread(Recive);
                th.IsBackground = true;
                th.Start(socketSend);
            }
        }
        
        void Recive(object o)
        {
            socketSend = o as Socket;
            while (true)
            {
                // 客户端连接成功后,服务器应接受客户端发来的消息
                byte[] buffer = new byte[1024 * 1024 * 2];
                // 实际接收到的有效字节数
                int r = socketSend.Receive(buffer);
                if (r == 0)
                {
                    break;
                }
                string str = Encoding.UTF8.GetString(buffer, 0, r);
                ShowMsg(socketSend.RemoteEndPoint + " : " + str);
            }
        }

        

        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "rn");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text;
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            string ip = cboUsers.SelectedItem.ToString();
            dicSocket[ip].Send(buffer);
            //socketSend.Send(buffer);
            txtMsg.Text = "";
        }

        private void btnSendUser_Click(object sender, EventArgs e)
        {
            string json = JsonConvert.SerializeObject(UserList());
            byte[] buffer = Encoding.UTF8.GetBytes(json);
            socketSend.Send(buffer);
        }

        private List<User> UserList()
        {
            List<User> userList = new List<User>();
            User user = null;
            string sql = "select * from user_table";
            SqlCommand cmd = SqlUtils.ConnectSql(sql);
            SqlDataReader sdr = cmd.ExecuteReader();
            while (sdr.Read())
            {
                user = new User(sdr.GetInt32(0), sdr.GetString(1), sdr.GetString(2), sdr.GetInt32(3));
                userList.Add(user);
            }
            return userList;
        }

    }
}

客户端

namespace TestClient
{
    public partial class ClientForm : Form
    {
        Socket socketSend;
        public ClientForm()
        {
            InitializeComponent();
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            try
            {
                // 创建负责通信的socket
                socketSend = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                IPEndPoint point = new IPEndPoint(ip,Convert.ToInt32(txtPort.Text));
                socketSend.Connect(point);
                ShowMsg("连接成功");
                Thread th = new Thread(Recive);
                th.IsBackground = true;
                th.Start();
            }
            catch { }
        }

        void Recive()
        {
            while (true)
            {
                // 客户端连接成功后,服务器应接受客户端发来的消息
                byte[] buffer = new byte[1024 * 1024 * 2];
                // 实际接收到的有效字节数
                int r = socketSend.Receive(buffer);
                if (r == 0)
                {
                    break;
                }
                string str = Encoding.UTF8.GetString(buffer, 0, r);
                ShowMsg(socketSend.RemoteEndPoint + " : " + str);
            }
        }

        void ShowMsg(string str)
        {
            txtLog.AppendText(str + "rn");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            string str = txtMsg.Text.Trim();
            byte[] buffer = Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
            txtMsg.Text = "";
        }
    }
}

效果

发送json数据

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持靠谱客。

最后

以上就是怡然溪流为你收集整理的C#实现套接字发送接收数据的全部内容,希望文章能够帮你解决C#实现套接字发送接收数据所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(99)

评论列表共有 0 条评论

立即
投稿
返回
顶部