我是靠谱客的博主 玩命自行车,这篇文章主要介绍C# TCP连接服务端与客户端的交互,现在分享给大家,希望可以做个参考。

效果图:客户端与服务端交互
在这里插入图片描述

服务端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
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 Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
        Socket remote = null;
        private void btnConnect_Click(object sender, EventArgs e)
        {
            //异步启动服务端
            Task.Run(() =>
            {
                Boolean running = true;
                //============================================================================//
                // 1、socket服务地址和监听端口
                //============================================================================//
                // socket服务地址
                string host = "127.0.0.1";
                // socket服务端口
                int port = 21000;
                // 将将IP地址字符串转换为IPAddress对象
                IPAddress ip = IPAddress.Parse(host);
                // 终结点EndPoint
                IPEndPoint ipe = new IPEndPoint(ip, port);

                //============================================================================//
                // 2、创建socket连接服务端并监听端口
                //============================================================================//
                //创建TCP Socket对象
                //绑定EndPoint对象(地址)
                server.Bind(ipe);
                //开始监听
                server.Listen(0);

                this.Invoke(new Action(() =>
                {
                    txtMsg.AppendText("已经处于监听状态,等待客户端连接...." + "rn");
                }));

                //============================================================================//
                // 3、与客户端交互
                //============================================================================//
                remote = server.Accept();

                while (running)
                {
                    if (server != null)
                    {
                        this.Invoke(new Action(() =>
                        {
                            txtMsg.AppendText("客户端连接...." + "rn");
                        }));
                        // 接收客户端消息
                        Receive(remote);
                        // 发送给客户端消息
                        Send(remote, "服务端已接收"+DateTime.Now.ToString());
                    }
                    Thread.Sleep(1000);
                }



                //============================================================================//
                // 4、关闭服务
                //============================================================================//
                //if (server != null)
                //{
                //    server.Close();
                //    server = null;
                //}
            });
        }

        void Receive(Socket socket)
        {
            byte[] bytes = new byte[1024];
            //从客户端接收消息
            int len = socket.Receive(bytes, bytes.Length, 0);
            //将消息转为字符串
            string recvStr = Encoding.UTF8.GetString(bytes, 0, len);
            this.Invoke(new Action(() =>
            {
                txtMsg.AppendText(string.Format("接收的客户端消息:{0}" + "rn", recvStr));
            }));
        }

        void Send(Socket socket, string sendStr)
        {
            this.Invoke(new Action(() =>
            {
                txtMsg.AppendText(string.Format("发送给客户端消息:{0}" + "rn", sendStr));
            }));
            // 将字符串消息转为数组
            byte[] bytes = Encoding.UTF8.GetBytes(sendStr);

            //发送消息给客户端
            socket.Send(bytes, bytes.Length, 0);
        }

        private void btnSendMsg_Click(object sender, EventArgs e)
        { 
            Send(remote, txtSendMsg.Text.Trim());
        }
    }
}

客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
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 Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        private void btnConnect_Click(object sender, EventArgs e)
        {
            //============================================================================//
            // 1、待连接的socket服务地址
            //============================================================================//
            string host = "127.0.0.1";
            int port = 21000;
            // 将将IP地址字符串转换为IPAddress对象
            IPAddress ip = IPAddress.Parse(host);
            // 创建终结点EndPoint
            IPEndPoint ipe = new IPEndPoint(ip, port);

            //============================================================================//
            // 2、创建socket连接客户端
            //============================================================================//        
            // 创建Socket并连接到服务器
            // 连接到服务器
            client.Connect(ipe);

            //============================================================================//
            // 3、与服务器端交互
            //============================================================================//
            Send(client, "我是一个客户端!");

            Task.Run(() =>
            {
                while (true)
                {
                    Receive(client);
                    //if (client != null)
                    //{
                    //    byte[] bytes = new byte[1024];
                    //    //从客户端接收消息
                    //    int len = client.Receive(bytes, bytes.Length, 0);
                    //    //将消息转为字符串
                    //    string recvStr = Encoding.UTF8.GetString(bytes, 0, len);
                    //    this.Invoke(new Action(() =>
                    //    {
                    //        txtMsg.AppendText(string.Format("接收的服务端消息 : {0}", recvStr) + "rn");
                    //    }));
                    //}
                    Thread.Sleep(1000);
                }

            });

            //============================================================================//
            // 4、关闭Socket连接
            //============================================================================//
            //if (client != null)
            //{
            //    client.Close();
            //    client = null;
            //}
        }

        /***
         * 发送消息
         */
        void Send(Socket socket, string sendStr)
        {
            this.Invoke(new Action(() =>
            {
                listBox1.Items.Add(string.Format("发送给服务端消息:{0}", sendStr) + "rnn");
            }));
            // 将字符串消息转为数组  
            byte[] bytes = Encoding.UTF8.GetBytes(sendStr);
            //发送消息给客户端
            socket.Send(bytes, bytes.Length, 0);
        }

        /// <summary>
        /// 接受服务端消息
        /// </summary>
        /// <param name="socket"></param>
        void Receive(Socket socket)
        {
            byte[] bytes = new byte[1024];
            //从客户端接收消息
            int len = socket.Receive(bytes, bytes.Length, 0);
            //将消息转为字符串
            string recvStr = Encoding.UTF8.GetString(bytes, 0, len);
            this.Invoke(new Action(() =>
            {
                listBox1.Items.Add(string.Format("接收的服务端消息 : {0}", recvStr) + "rn");
            }));
        }

        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            Send(client, txtSendMsg.Text.Trim());
        }
         
    }
}

需要这个dome可联系QQ1442601713

最后

以上就是玩命自行车最近收集整理的关于C# TCP连接服务端与客户端的交互的全部内容,更多相关C#内容请搜索靠谱客的其他文章。

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

评论列表共有 0 条评论

立即
投稿
返回
顶部