Socket客户端

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class MainFrmC : Form
    {
        public Socket ClientSocket { get; set; }
        public MainFrmC()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            //创建Socket对象
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            ClientSocket = socket;
            //连接服务器        
            try
            {
                socket.Connect(IPAddress.Parse(txtIP.Text), int.Parse(txtPort.Text));
            }
            catch (Exception ex)
            {
                MessageBox.Show("重新连接....");
            }

            //发送消息
            Thread thread = new Thread(new ParameterizedThreadStart(ReceiveData));
            thread.IsBackground = true;
            thread.Start(ClientSocket);
        }
        private void btnStart_Click(object sender, EventArgs e)
        {
          
        }

        public void ReceiveData(object socket)
        {
            var proxSocket = socket as Socket;
            byte[] data = new byte[1024 * 1024];
            while (true)
            {
                int len = 0;
                try
                {
                    len = proxSocket.Receive(data, 0, data.Length, SocketFlags.None);
                }
                catch (Exception ex)
                {
                    //异常退出
                    AppendTextToTxtLog(string.Format("服务端{0}:非正常退出", proxSocket.RemoteEndPoint.ToString()));
                    StopConnet();
                    return;
                }


                if (len <= 0)
                {
                    //客户端正常退出
                    AppendTextToTxtLog(string.Format("服务端{0}:正常退出", proxSocket.RemoteEndPoint.ToString()));
                    StopConnet();
                    return;
                }

                //把接收的数据放文本框上面
                string str = Encoding.Default.GetString(data, 0, len);
                AppendTextToTxtLog(string.Format("接收客户端:{0}的消息是:{1}", proxSocket.RemoteEndPoint.ToString(), str));

                //闪屏
                if (data[0] == 2)
                {
                    Shake();
                }


                //接收文件
                if (data[0] == 3)
                {
                    ProcessReciveFile(data,len);
                }

            }
        }


        /// <summary>
        /// 接收文件
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private void ProcessReciveFile(byte[] data,int len)
        {
            using (SaveFileDialog sfd = new SaveFileDialog())
            {
                sfd.DefaultExt = "txt";
                sfd.Filter = "文本文件(*.txt)|*.txt|所有文件(*.*)|*.*";
                if (sfd.ShowDialog(this) != DialogResult.OK)
                {
                    return;
                }
                byte[] fileDate=new byte[len-1];
                Buffer.BlockCopy(data,1,fileDate,0,len-1);
                File.WriteAllBytes(sfd.FileName, fileDate);
            }
        }


        /// <summary>
        /// 闪屏
        /// </summary>
        private void Shake()
        {
            //记录原始坐标
            Point oldLocation = this.Location;
            Random r=new Random();

            for (int i = 0; i < 50; i++)
            {
                this.Location = new Point(r.Next(oldLocation.X - 5,oldLocation.X + 5), r.Next(oldLocation.Y - 5, oldLocation.Y + 5));//确定震荡范围
                Thread.Sleep(50);
                this.Location = oldLocation;
            }
        }

        private void StopConnet()
        {
            if (ClientSocket.Connected)
            {
                ClientSocket.Shutdown(SocketShutdown.Both);
                ClientSocket.Close(100);
            }
        }

        public void AppendTextToTxtLog(string txt)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke(new Action<string>
                    (s => { this.txtLog.Text = string.Format("{0}\r\n{1}", s, txtLog.Text); })
                    , txt);
            }
            else
            {
                this.txtLog.Text = string.Format("{0}\r\n{1}", txt, txtLog.Text);
            }
        }




        private void btnSendMsg_Click(object sender, EventArgs e)
        {
            
        }

        private void txtPort_TextChanged(object sender, EventArgs e)
        {

        }

        private void btnSendMsg_Click_1(object sender, EventArgs e)
        {
            if (ClientSocket.Connected)
            {
                byte[] data = Encoding.Default.GetBytes(txtMsg.Text);
                ClientSocket.Send(data, 0, data.Length, SocketFlags.None);
            }
        }

        private void txtIP_TextChanged(object sender, EventArgs e)
        {

        }

        private void txtLog_TextChanged(object sender, EventArgs e)
        {

        }

        private void label1_Click(object sender, EventArgs e)
        {

        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值