WPF Socket客户端(重连)

主界面的设计

<Window x:Class="SocketClient.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:SocketClient"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525" ShowInTaskbar="False" IsHitTestVisible="True">
    <Grid>
        <Grid.RowDefinitions>
            <!--按照比例划分单元格-->
            <RowDefinition Height="9*"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <!--富文本来显示接收的内容-->
        <RichTextBox Name="tb_receive" Grid.Row="0" Background="Black" Foreground="White" FontSize="20"></RichTextBox>
        <!--文本框显示需要发送的内容-->
        <TextBox Name="tb_send" Grid.Row="1" VerticalAlignment="Center" FontSize="18"></TextBox>
    </Grid>
</Window>

主界面的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Diagnostics;

namespace SocketClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {

        private SocketManager socketMgr = null;

        public MainWindow()
        {
            InitializeComponent();

            //添加按键监听事件//
            tb_send.KeyUp += new KeyEventHandler(TextBox_KeyUp);

            //添加点击监听事件//
            //btn_send.Click += new RoutedEventHandler(Btn_Click);

            //连接服务端//
            socketMgr = new SocketManager(this);
            socketMgr.Connect("172.16.3.230", 1234);
        }

        //点击事件//
        private void Btn_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            switch(btn.Name)
            {
                case "btn_send":
                    socketMgr.Send(tb_send.Text);
                    break;
            }
        }

        //接收数据//
        public void ReceiveData(string str)
        {
            //委托事件把线程的数据传递给UI界面//
            Action receiveDelegate = delegate ()
              {
                  str += "\r";
                  tb_receive.AppendText(str);
              };
            this.Dispatcher.BeginInvoke(receiveDelegate);
        }

        //文本框的按键监听事件//
        private void TextBox_KeyUp(object sender, KeyEventArgs e)
        {
           switch(e.Key)
            {
                case Key.Enter:
                    //发送并清空//
                    socketMgr.Send(tb_send.Text);
                    tb_send.Text = "";
                    break;
            }
        }

        //关闭程序事件//
        protected override void OnClosed(EventArgs e)
        {
            Debug.WriteLine("closed....\n\n");
            if (socketMgr!=null)
            {
                socketMgr.Close();
            }

        }
    }
}

SocketManager的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Windows;

namespace SocketClient
{

    public class SocketManager
    {
        private bool isConnected = false;//是否连接//
        private bool isClosed = false;//软件是否关闭//

        private Socket clientSocket=null;//客户端SOCKET//

        MainWindow win = null;//主界面//

        private byte[] receive_buffer = new byte[2048];

        public SocketManager(MainWindow window)
        {
            win = window;
        }

        public void Connect(string ip,int port)
        {
            //重连线程//
            Thread reconnectThread = new Thread(ReconnectFunction);

            IPAddress ipAddr = IPAddress.Parse(ip);
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, port);

            reconnectThread.Start((object)ipEndPoint);

            //接收数据线程//
            Thread receiveThread = new Thread(ReceiveFunction);
            receiveThread.Start();

            //发送心跳线程//
            Thread jumpHeartThread = new Thread(JumpHeartFunction);
            jumpHeartThread.Start();
        }

        private void JumpHeartFunction()
        {
            while(true)
            {
                if (isClosed)
                {
                    break;
                }
                if (isConnected)
                {
                    try
                    {
                        Send("1");
                        Thread.Sleep(5000);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("Exception:{0}\n", e);
                        isConnected = false;
                    }


                }
            }
        }

        private void ReceiveFunction()
        {
            while(true)
            {
                if(isClosed)
                {
                    break;
                }
                if(isConnected)
                {
                    try
                    {
                        int len = clientSocket.Receive(receive_buffer);

                        if(len==0)
                        {
                            isConnected = false;
                            continue;
                        }

                        string receive_str = Encoding.GetEncoding("GBK")
                            .GetString(receive_buffer, 0, len);

                        if (win!=null)
                        {
                            win.ReceiveData(receive_str);
                        }

                        Debug.WriteLine("Receive:{0}\n\n", receive_str);
                    }
                    catch(Exception e)
                    {
                        Debug.WriteLine("Exception:{0}\n",e);
                        isConnected = false;
                    }


                }
            }
        }

        public void Close()
        {
            clientSocket.Shutdown(SocketShutdown.Both);
            clientSocket.Close();
            isClosed = true;
            isConnected = false;                       
        }

        public void Send(byte[] byte_msg)
        {
            try
            {
                clientSocket.Send(byte_msg);
            }
            catch(Exception e)
            {
                Debug.WriteLine("Exception...{0}",e);
                isConnected = false;
            }

        }

        public void Send(string string_msg)
        {
            try
            {
                byte[] sendBytes = Encoding.GetEncoding("GBK").GetBytes(string_msg);
                clientSocket.Send(sendBytes);
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception...{0}", e);
                isConnected = false;
            }
        }

        private void ReconnectFunction(object parameter)
        {
            IPEndPoint ipEndPoint = (IPEndPoint)parameter;

            while (true)
            {
                if(isClosed)
                {
                    break;
                }

                if(!isConnected)
                {
                    try
                    {
                        clientSocket = new Socket(AddressFamily.InterNetwork, 
                            SocketType.Stream,ProtocolType.Tcp);
                        clientSocket.Connect(ipEndPoint);

                        isConnected = true;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine("Exception:{0}", e);
                        isConnected = false;
                        clientSocket = null;
                    }
                }               
                Thread.Sleep(1000);
            }
        }
    }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值