C# Socket案例(服务端与客户端)

服务端完整代码

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ServerSocket
{
    public partial class Form1 : Form
    {
        //定义Socket对象
        Socket serverSocket;
        //定义监听线程
        Thread listenThread;
        //定义接收客户端数据线程
        Thread threadReceive;
        //定义双方通信
        Socket socket;
        string str;

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse(this.text_ip.Text.Trim());
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try {
                //绑定ip和端口
                serverSocket.Bind(new IPEndPoint(ip, Convert.ToInt32(this.text_port.Text.Trim())));
                //设置最多10个排队连接请求
                serverSocket.Listen(10);
                //开启线程循环监听
                listenThread = new Thread(ListenClientConnect);
                listenThread.Start();
                this.button_start.Enabled = false;
                
            } catch {
                MessageBox.Show("监听异常", "监听异常");
            }
            
        }

        //监听
        private void ListenClientConnect()
        {
            while (true) {
                //监听到客户端的连接,获取双方通信socket
                socket = serverSocket.Accept();
                //创建线程循环接收客户端发送的数据
                threadReceive = new Thread(Receive);
                //传入双方通信socket
                threadReceive.Start(socket);
            }
        }

        //接收客户端数据
        private void Receive(object socket)
        {
            try {
                Socket myClientSocket = (Socket)socket;
                while (true) {
                    byte[] buff = new byte[20000];
                    int r = myClientSocket.Receive(buff);
                    str = Encoding.Default.GetString(buff, 0, r);                  
                    this.Invoke(new Action(() => { this.text_log1.Text = str; }));
                }
            } catch {
                MessageBox.Show("接收数据失败", "接收数据失败");
            }
        }

        //关闭
        private void button_close_Click(object sender, EventArgs e)
        {
            //socket关闭
            serverSocket.Close();
            //线程关闭
            listenThread.Abort();
            threadReceive.Abort();
        }

        //发送
        private void button_send_Click(object sender, EventArgs e)
        {
            try
            {
                string strMsg = this.text_log2.Text.Trim();
                byte[] buffer = new byte[20000];
                buffer = Encoding.Default.GetBytes(strMsg);
                socket.Send(buffer);
            }
            catch
            {
                MessageBox.Show("发送数据失败", "发送数据失败");
            }
        }
    }
}

客户端完整代码

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace ClientSocket
{
    public partial class Form1 : Form
    {
        //定义Socket对象
        Socket clientSocket;
        //创建接收消息的线程
        Thread threadReceive;
        //接收服务端发送的数据
        string str;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void button_connect_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse(this.text_ip.Text.Trim());
            clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try {
                //连接服务端
                clientSocket.Connect(ip, Convert.ToInt32(this.text_port.Text.Trim()));
                //开启线程不停的接收服务端发送的数据
                threadReceive = new Thread(new ThreadStart(Receive));
                threadReceive.IsBackground = true;
                threadReceive.Start();
                //设置连接按钮在连接服务端后状态为不可点
                this.button_connect.Enabled = false;
            } catch {
                MessageBox.Show("连接服务端失败,请确认ip和端口是否填写正确", "连接服务端失败");
            }
        }

        //接收服务端消息的线程方法
        private void Receive()
        {
            try {
                while (true) {
                    byte[] buff = new byte[20000];
                    int r = clientSocket.Receive(buff);
                    str = Encoding.Default.GetString(buff,0,r);
                    this.Invoke(new Action(() => { this.text_log1.Text = str; }));
                }
            } catch {
                MessageBox.Show("获取服务端参数失败","获取服务端参数失败");
            }
        }

        private void button_close_Click(object sender, EventArgs e)
        {
            //clientSocket关闭
            clientSocket.Close();
            //threadReceive关闭
            threadReceive.Abort();
        }

        private void button_send_Click(object sender, EventArgs e)
        {
            try {
                string strMsg = this.text_log2.Text.Trim();
                byte[] buffer = new byte[20000];
                buffer = Encoding.Default.GetBytes(strMsg);
                clientSocket.Send(buffer);
            } catch {
                MessageBox.Show("发送数据失败", "发送数据失败");
            }
        }
    }
}

编译成功后点击发送效果图

具体步骤(思路)

服务器端:
第一步:创建一个用于监听连接的Socket对像;
第二步:用指定的端口号和服务器的ip建立一个EndPoint对像;
第三步:用socket对像的Bind()方法绑定EndPoint;
第四步:用socket对像的Listen()方法开始监听;

第五步:接收到客户端的连接,用socket对像的Accept()方法创建一个新的用于和客户端进行通信的socket对像;

第六步:通信结束后一定记得关闭socket;

客户端:
第一步:建立一个Socket对像;
第二步:用指定的端口号和服务器的ip建立一个EndPoint对像;
第三步:用socket对像的Connect()方法以上面建立的EndPoint对像做为参数,向服务器发出连接请求;
第四步:如果连接成功,就用socket对像的Send()方法向服务器发送信息;
第五步:用socket对像的Receive()方法接受服务器发来的信息 ;

第六步:通信结束后一定记得关闭socket;

https://blog.csdn.net/qq_42203978/article/details/80520299

原文地址:https://www.cnblogs.com/xihong2014/p/13677250.html