当前位置: 首页 > article >正文

Socket服务器和客户端

服务器

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 socket服务器
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 开始监听
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            //1创建套接字
            //1 AddressFamily.InterNetwork ipv4的地址
            //2 SocketType.Stream 数据格式 以数据流的方式传输
            //3 ProtocolType.Tcp 采用的协议
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2 绑定ip和端口号
            IPAddress ip =IPAddress.Parse(textBox1.Text); //创建ip
            //1 ip地址
            //2 端口号
            IPEndPoint point = new IPEndPoint(ip,int.Parse(textBox2.Text));
            socket.Bind(point);// 绑定端口号

            //3监听端口号
            socket.Listen(1000);

            //4 接收客户端发来的连接消息 创建线程进行接收
            Thread th = new Thread(Connect);
            th.Start(socket);//开启线程传递socket


        }
        public void Connect(object o)
        {
            Socket s1 = o as Socket;
            try
            {
                while (true) //接收客户端连接
                {
                    Socket c1 = s1.Accept();//接收客户端连接
                    //c1是客户端
                    //s1是服务器
                    this.Invoke(new Action(() =>
                    {
                        richTextBox1.Text += $"{DateTime.Now.ToString("F")}-{c1.RemoteEndPoint}-连接成功"+"\n";
                    }));

                    //5收发数据 写在线程里面
                    Thread t2 = new Thread(ReceiveMsg);
                    t2.Start(c1);
                }

            }
            catch (Exception)
            {

                throw;
            }


        }
        //接收消息的线程方法
        Socket ss = null;
        public void ReceiveMsg(object o)
        {
             ss = o as Socket;
            try
            {
                byte[] buffer = new byte[1024];//定义缓存区 长度1024
                while (true)//一直接收数据
                {
                    int length =  ss.Receive(buffer); //接收数据实际长度 
                    string str = Encoding.UTF8.GetString(buffer, 0, length);

                    //显示到界面上
                    this.Invoke(new Action(() =>
                    {
                        richTextBox1.Text += $"接收到来自客户端的消息:"+str + "\r\n";
                    }));
                    //6 服务器转发消息


                }
            }
            catch (Exception)
            {

                Console.WriteLine("客户端下线");
            }


        }
        /// <summary>
        /// 发消息
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            if (ss != null)
            {
                byte[] bs = Encoding.UTF8.GetBytes(textBox3.Text);
                richTextBox1.Text += $"服务器发送的消息:" + textBox3.Text +"\n";
                ss.Send(bs); //发送客户端
            }

        }
        /// <summary>
        /// 断开连接
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {

        }

       
    }
}

客户端 

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 _2socket客户端
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 连接服务器
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        Socket socket = null;
        private void button2_Click(object sender, EventArgs e)
        {
            //1创建socket客户端对象
             socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //2 连接指定服务器
            socket.Connect(new IPEndPoint(IPAddress.Parse("192.168.107.14"), 3030));

            //3 接收服务器发的消息
            Thread th = new Thread(ReceiveMsg);
            th.Start();

        }
        //接收服务器发来的消息
        public void ReceiveMsg()
        {
            try
            {
                byte[]  buffer = new byte[1024];
                while (true)
                {
                   int length =  socket.Receive(buffer); //接收服务器数据,保存buffer数组
                   string str =  Encoding.UTF8.GetString(buffer, 0, length);
                    this.Invoke(new Action(() =>
                    {
                        richTextBox1.Text += str + "\n";
                    }));
                }
            }
            catch (Exception)
            {

                throw;
            }

        }


        //发送消息
        private void button1_Click(object sender, EventArgs e)
        {
            //4 发送消息
            Thread th = new Thread(SendMsg);
            th.Start();
        }
        //发消息的线程方法
        public void SendMsg()
        {
            if(socket!=null)
            {
                byte[] bs = Encoding.UTF8.GetBytes(textBox1.Text);// 获取输入框文本并且转成字节数组
                socket.Send(bs);
            }
        }

    }
}






http://www.kler.cn/a/587065.html

相关文章:

  • 安装SQL数据库并且在jupyter中连接,运行
  • 回溯法--力扣第17题“电话号码的字母组合”(java)
  • 【初级篇】如何使用DeepSeek和Dify构建高效的企业级智能客服系统
  • stable Diffusion 中的 VAE是什么
  • Maximize Rating
  • [动手学习深度学习]24. AlexNet
  • 神经网络的基本知识
  • 补充二分LIS
  • 【公务员考试】高效备考指南
  • 2018年全国职业院校技能大赛高职组-计算机网络应用竞赛竞赛样题F卷
  • 【C++】—— 一篇文章解决面试 继承菱形继承
  • A SURVEY ON POST-TRAINING OF LARGE LANGUAGE MODELS——大型语言模型的训练后优化综述——第一部分
  • 加密算法逆向与HOOK技术实战
  • OpenHarmony子系统开发 - ArkCompiler开发指导
  • matlab 控制系统GUI设计-PID控制超前滞后控制
  • 打靶日记Kioptix Level 4
  • vue项目如何实现条件查询?
  • 贪吃蛇小游戏-简单开发版
  • 【实战ES】实战 Elasticsearch:快速上手与深度实践-附录-2-性能调优工具箱
  • 路由器和网关支持边缘计算