C#Socket

socket自动断线

首先断线有很多可能,服务器端代码错误或者网络路由问题,等等,解决这些断线问题的方法就是心跳检测,看应用需要采用几秒客户端(C)向服务器端发送【ping】协议(协议名称可以自己定)。然后服务器(S)要有个储存器(可以是哈希表或者是类数组)保存客户端连接句柄以及一些必要属性,还要有个时间,用来对比C每次ping的时间是否超过设定超时时间。如果超时就将C的Sock 句柄清除。到这S端就可以了。C端还要有个断线处理,监视检测自己是否断线,做个重连机制,这样一个完整的通讯就差不多了,至于其他应用就要看自己的需要通过协议来操作了。 希望这些能帮到你

一、服务端

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.Windows.Forms;

namespace DXApplication1
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //实例化套接字(IP4寻找协议,流式协议,TCP协议)
            Socket SocketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //创建IP对象
            IPAddress IP_Server = IPAddress.Any;

            //创建网络端口(包括IP和端口)
            IPEndPoint point = new IPEndPoint(IP_Server, Convert.ToInt32(IP_Port.Text));
            //绑定套接字
            SocketWatch.Bind(point);
            //设置监听的最大连接数(超出范围进行排队)
            SocketWatch.Listen(int.MaxValue);
            ShowServerMSG("监听"+ SocketWatch.LocalEndPoint.ToString()+"成功");

            Thread thread = new Thread(ListenClieentConnect);
            thread.IsBackground = true;
            thread.Start(SocketWatch);
        }

        private void ListenClieentConnect(object o)
        {
            Socket SocketWatch = o as Socket;
            while (true)
            {
                //创建新的连接,产生一个用于通信的Socket
                Socket ClientSocket = SocketWatch.Accept();
                ShowServerMSG(ClientSocket.RemoteEndPoint.ToString() + ": 客户端连接成功");
                Thread thread = new Thread(SocketReceive);
                thread.IsBackground = true;
                thread.Start(ClientSocket);
            }
        }

        private void SocketReceive(object o)
        {
            Socket ClientSocket = o as Socket;
            while (true)
            {
                //客户端连接成功后应该接受客户端发过来的消息
                Byte[] buff = new Byte[1024 * 1024 * 2];
                int r = ClientSocket.Receive(buff);
                if (r==0 || r==null)
                {
                    break;
                }
                //显示一下客户端发来的消息
                string str = Encoding.UTF8.GetString(buff, 0, r);
                ShowServerMSG(ClientSocket.RemoteEndPoint.ToString() + ": " + str);
            }
        }

        private void ShowServerMSG(string str)
        {
            rtb_Server.AppendText(str+'
'+'
');
        }

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

二、客户端

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.Windows.Forms;

namespace Client
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        public Form1()
        {
            InitializeComponent();
        }
        Socket ClientSocket;
        private void bt_Connect_Click(object sender, EventArgs e)
        {
            
            ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipServer = IPAddress.Parse(txt_IPServer.Text);
            IPEndPoint point = new IPEndPoint(ipServer,Convert.ToInt32(txt_IPPort.Text));

            ClientSocket.Connect(point);
        }

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

        private void bt_ClientSend_Click(object sender, EventArgs e)
        {
            string msg = rtb_Client.Text;
            Byte[] buffer = System.Text.Encoding.UTF8.GetBytes(msg);
            ClientSocket.Send(buffer);
        }
    }
}
原文地址:https://www.cnblogs.com/javier520/p/10816493.html