zoukankan      html  css  js  c++  java
  • Socket-客户端向服务器端发送消息

    客户端:

    界面:

     代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    
    namespace Test2.Client
    {
        public partial class Form1 : Form
        {
            Socket clientSocket;
            IPEndPoint ipEndPoint;
            public Form1()
            {
                InitializeComponent();
                button1.Text = "连接";
                button2.Text = "发送";
                button3.Text = "关闭";
            }
            private void button1_Click(object sender, EventArgs e)
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ipEndPoint = new IPEndPoint(IPAddress.Parse("xxxxxxxxx"), 52555);
                clientSocket.Connect(ipEndPoint);
            }
    
            private void button2_Click(object sender, EventArgs e)
            {
                clientSocket.Send(System.Text.Encoding.UTF8.GetBytes(textBox1.Text));
                
            }
    
            private void button3_Click(object sender, EventArgs e)
            {
                SafeClose(clientSocket);
            }
            public  void SafeClose( Socket socket)
            {
                if (socket == null)
                    return;
    
                if (!socket.Connected)
                    return;
    
                try
                {
                    socket.Shutdown(SocketShutdown.Both);
                }
                catch
                {
                }
    
                try
                {
                    socket.Close();
                }
                catch
                {
                }
            }
        }
    }

    服务器端:

    界面:

     代码:

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.Windows.Forms;
    using System.Net;
    using System.Net.Sockets;
    using System.Threading;
    
    namespace Test2.Server
    {
        public partial class Form1 : Form
        {
      
            public Form1()
            {
                InitializeComponent();
                this.FormClosed += Form1_FormClosed;
            }
    
            private void Form1_FormClosed(object sender, FormClosedEventArgs e)
            {
                SafeClose(socketSend);
            }
            public void SafeClose( Socket socket)
            {
                if (socket == null)
                    return;
    
                if (!socket.Connected)
                    return;
    
                try
                {
                    socket.Shutdown(SocketShutdown.Both);
                }
                catch
                {
                }
    
                try
                {
                    socket.Close();
                }
                catch
                {
                }
            }
    
    
            Socket socketSend;
            private void button1_Click(object sender, EventArgs e)
            {
                try
                {
                    //点击开始监听时 在服务端创建一个负责监听IP和端口号的Socket
                    Socket socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                    IPAddress ip = IPAddress.Any;                //创建对象端口
                    IPEndPoint point = new IPEndPoint(ip, Convert.ToInt32(52555));
                    socketWatch.Bind(point);//绑定端口号
                    MessageBox.Show("Watching");
                    socketWatch.Listen(10);//设置监听
                                           //创建监听线程
                    Thread thread = new Thread(Listen);
                    thread.IsBackground = true;
                    thread.Start(socketWatch);
                }
                catch { }
    
            }
    
            void Listen(object o)
            {
                try
                {
                    Socket socketWatch = o as Socket;
                    while (true)
                    {
                        socketSend = socketWatch.Accept();//等待接收客户端连接
                        //ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
                        //开启一个新线程,执行接收消息方法
                        Thread r_thread = new Thread(Received);
                        r_thread.IsBackground = true;
                        r_thread.Start(socketSend);
                    }
                }
                catch { }
            }
    
            void Received(object o)
            {
                try
                {
                    Socket socketSend = o as Socket;
                    while (true)
                    {
                        //客户端连接服务器成功后,服务器接收客户端发送的消息
                        byte[] buffer = new byte[1024 * 1024 * 3];
                        //实际接收到的有效字节数
                        int len = socketSend.Receive(buffer);
                        if (len == 0)
                        {
                            break;
                        }
                        string str = Encoding.UTF8.GetString(buffer, 0, len);
    
                        this.Invoke(new Action(() =>
                        {
                            listBox1.Items.Add(str + "
    ");
                        }));
                    }
                }
                catch { }
            }
        }
    }

     ps:当客户端使用connect方法连接服务器端时,服务端的accept方法接受请求,并且此时可以向客户端发送消息:

    代码如下:

    客户端:

       private void button1_Click(object sender, EventArgs e)
            {
                clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                ipEndPoint = new IPEndPoint(IPAddress.Parse("xxxxxx"), 52555);
                clientSocket.Connect(ipEndPoint);
                byte[] mybyte = new byte[1024 * 1024];
                Task.Run(() => 
                {
                   int length= clientSocket.Receive(mybyte);
                    string str = System.Text.Encoding.UTF8.GetString(mybyte, 0, length);
                    this.textBox1.Invoke(new Action(()=> 
                    {
    
                        this.textBox1.Text = str;
                    }));
                });
            }

    服务器端:

      void Listen(object o)
            {
                try
                {
                    Socket socketWatch = o as Socket;
                    while (true)
                    {
                        socketSend = socketWatch.Accept();//等待接收客户端连接
                        Task.Run(() => 
                        {
                            //string str = "123";
    
                            socketSend.Send(System.Text.Encoding.UTF8.GetBytes("123"));
                        });
                        //ShowMsg(socketSend.RemoteEndPoint.ToString() + ":" + "连接成功!");
                        //开启一个新线程,执行接收消息方法
                        Thread r_thread = new Thread(Received);
                        r_thread.IsBackground = true;
                        r_thread.Start(socketSend);
                    }
                }
                catch { }
            }
  • 相关阅读:
    The Sixth Assignment
    The fifth assigiment
    网络编程
    面向对象
    python数据类型之集合
    python数据类型之列表
    python数据类型之字符串
    python数据类型之字典
    python数据类型之元组
    常用模块
  • 原文地址:https://www.cnblogs.com/dangnianxiaoqingxin/p/13226419.html
Copyright © 2011-2022 走看看