• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

.netsocket双向通信小程序

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

 完整代码:https://git.dev.tencent.com/pingaq/socket.git(腾讯云)

//服务端代码
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 WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnstart_Click(object sender, EventArgs e)
        {
            //当点击开始监听的时候,在服务器端创建一个负责监视IP地址和端口好的socket
            Socket socketwatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream,ProtocolType.Tcp);
            IPAddress ip = IPAddress.Any;
            //创建端口号对象
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));
            //监听
            socketwatch.Bind(point);
            ShowMsg("监听成功");
            socketwatch.Listen(10);

            Thread th = new Thread(listen);
            th.IsBackground = true;
            th.Start(socketwatch);
        }
        Socket socketsend;
        /// <summary>
        /// 等待客户端的连接,并创建一个负责通信的socket
        /// </summary>
        void listen(object o)
        {
            Socket socketwatch = o as Socket;
            //等待客户的连接,兵创建一个负责通信得到socket
            while (true)
            {
                //负责和客户端通信的socket
                socketsend = socketwatch.Accept();
                disSocket.Add(socketsend.RemoteEndPoint.ToString(),socketsend);
                //存入下拉框中
                comboBox1.Items.Add(socketsend.RemoteEndPoint.ToString());
                ShowMsg(socketsend.RemoteEndPoint.ToString() + ":" + "连接成功");
                //开启一个新线程不停的接受消息
                Thread th = new Thread(Recive);
                th.IsBackground = true;
                th.Start(socketsend);
            }
        }
        /// <summary>
        /// 将远程连接的客户端的ip和socket存入集合中
        /// </summary>
        Dictionary<string, Socket> disSocket = new Dictionary<string, Socket>();
        /// <summary>
        /// 服务器不停的接受客户端发送过来的消息
        /// </summary>
        /// <param name="o"></param>
        void Recive(object o)
        {
            Socket socketsend = o as Socket;
            while (true)
            {
                try
                {
                    //客户端连接成功后,服务器端应该接受客户端发来的消息

                    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);
                }
                catch
                {

                }
               
            }
           
        }
        void ShowMsg(string str)
        {
            richTextBox1.Text+=(str + "\r\n");
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Control.CheckForIllegalCrossThreadCalls = false;
        }
        /// <summary>
        /// 服务器给客户端发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            string str = richTextBox2.Text;
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            string ip = comboBox1.Text;
            socketsend.Send(buffer);

        }
    }
}
//客户端代码
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 WindowsFormsApp2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket socketSend;
        private void button1_Click(object sender, EventArgs e)
        {
            //创建负责通信的socket
             socketSend = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse(textBox1.Text);
            IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(textBox2.Text));
            //获得远程的服务器ip和端口号
            socketSend.Connect(point);
          
             showMsg("连接成功");
            //开启一个新的线程不停的接受服务器发来的消息
            Thread th = new Thread(Revice);
            th.IsBackground = true;
            th.Start();
        }
        /// <summary>
        /// 不停接受服务器发来的消息
        /// </summary>
        void Revice()
        {
            while (true)
            {
                byte[] buffer = new byte[1024 * 1024 * 3];
                //实际接收到的有限字节数
                int r = socketSend.Receive(buffer);
                if (r == 0)
                {
                    break;
                }
                string s = Encoding.UTF8.GetString(buffer, 0, r);
                showMsg(socketSend.RemoteEndPoint+":"+s);
            }
        }
        void showMsg(string str)
        {
            richTextBox1.Text += (str + "\r\n");
        }
        /// <summary>
        /// 客户端给服务器发送消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            string str = richTextBox2.Text.Trim();
            byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
            socketSend.Send(buffer);
        }

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

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
微信小程序教程案例 - 烟雨观春柳发布时间:2022-07-18
下一篇:
小程序云开发--第一天(才接触)发布时间:2022-07-18
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap