• C# socket 客户端


    //这里创建的是负责通信的socket,这个socket 不分 服务器或客户端
            public  static Socket socketCommunication = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    
    
            public Form1()
            {
                InitializeComponent();
            }
    
            //打开链接   服务器
            private void button2_Click(object sender, EventArgs e)
            {
                IPAddress ip = IPAddress.Parse(txtServer.Text);
                IPEndPoint point = new IPEndPoint(ip, int.Parse(txtPort.Text));
                try
                {
                    socketCommunication.Connect(point);
                    DateTime dt = DateTime.Now;
                    dt.ToUniversalTime().ToString();
                    this.listBox1.Items.Add(dt.ToUniversalTime().ToString() + "链接成功");
                }
                catch (Exception e1)
                {
                    Console.WriteLine("Thread aborted.");
                    socketCommunication.Connect(point);
                    DateTime dt = DateTime.Now;
                    dt.ToUniversalTime().ToString();
                    this.listBox1.Items.Add(dt.ToUniversalTime().ToString() + "链接失败");
                }
    
            }
    
            //发送数据
            private void button1_Click(object sender, EventArgs e)
            {
    
                //接受
                string recvStr = "";
                byte[] recvBytes = new byte[1024];
                int bytes;
                bytes = socketCommunication.Receive(recvBytes, recvBytes.Length, 0);
                recvStr = Encoding.UTF8.GetString(recvBytes, 0, bytes);
    
    
                //发送
                string str = "vsvvsvd";
                //把要发送的消息转为字节数组
                byte[] buffer = System.Text.Encoding.UTF8.GetBytes(str);
                socketCommunication.Send(buffer);
                //
                socketCommunication.Close();
            }
  • 相关阅读:
    C++ CheckListBox
    TreeView查获节点并选中节点
    创建文件自动重命名
    bat
    Edit显示行号
    FindStringExact
    Extended ComboBox添加图标
    C++ Combobox输入时自动完成
    C++ ComboBox基础
    C++ Code_combobox
  • 原文地址:https://www.cnblogs.com/wenluderen/p/15200303.html
Copyright © 2020-2023  润新知