关于socket用winform实现简单通信 大牛可绕道 初学者可以看看 我做的时候把客户端窗口隐藏了 大家可以自己改一下

2/22/2017来源:ASP.NET技巧人气:2323

服务器端

using System;

using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace TcpFrmServer {     public partial class Form1 : Form     {         List<Socket> PRoxSocketList = new List<Socket>();         public Form1()         {             InitializeComponent();         }         //public object Threadpool { get; private set; }         private void btnStart_Click(object sender, EventArgs e)         {         }         public void Connect(object socket)         {             var serverSocket = socket as Socket;             this.TextToLog("服务器端开始接受消息");             while (true)             {                 var proxSocket = serverSocket.Accept();                 this.TextToLog(string.Format("客户端:{0}链接到位", proxSocket.RemoteEndPoint.ToString()));                 ProxSocketList.Add(proxSocket);                 ThreadPool.QueueUserWorkItem(new WaitCallback(Data), proxSocket);             }         }         public void Data(object socket)         {             var proxSocket = socket as Socket;             byte[] b = new byte[1024 * 1024];             int i = 0;             while (true)             {                 try                 {                     i = proxSocket.Receive                          (b, 0, b.Length, SocketFlags.None);                 }                 catch (Exception ex)                 {                     TextToLog                  (string.Format("接收到客户端:{0}错误", proxSocket.RemoteEndPoint.ToString()));                     ProxSocketList.Remove(proxSocket);                     Connetct(proxSocket); //                     return;                 }                 if (i <= 0)                 {                     TextToLog                    (string.Format("接收到客户端:{0}正常", proxSocket.RemoteEndPoint.ToString()));                     ProxSocketList.Remove(proxSocket);                     Connect(proxSocket);                     return;                 }                 string str = Encoding.Default.GetString(b, 0, i);                 TextToLog                     (string.Format("接收到客户端:{0}的消息:{1}", proxSocket.RemoteEndPoint.ToString(), str));             }         }         private void Connetct(Socket proxSocket)         {             try             {                 if (proxSocket.Connected)                 {                     proxSocket.Shutdown(SocketShutdown.Both);                     proxSocket.Close(100);                 }             }             catch (Exception ex)             {             }         }         public void TextToLog(string txt)         {             if (txtLog.InvokeRequired)             {                 txtLog.BeginInvoke(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);             }         }         /// <summary>         /// 发送         /// </summary>         /// <param name="sender"></param>         /// <param name="e"></param>         private void btnSendMsg_Click(object sender, EventArgs e)         {             foreach (var proxSocket in ProxSocketList)             {                 if (proxSocket.Connected)                 {                     byte[] data = Encoding.Default.GetBytes(txtMsg.Text);                     byte[] result = new byte[data.Length + 1];                     result[0] = 1;                     Buffer.BlockCopy(data, 0, result, 1, data.Length);                     proxSocket.Send(data, 0, data.Length, SocketFlags.None);                 }             }         }         private void Form1_Load(object sender, EventArgs e)         {             Socket socket = new Socket                (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);             socket.Bind(new ipEndPoint(IPAddress.Parse("地址"),65530));             socket.Listen(10);             ThreadPool.QueueUserWorkItem(new WaitCallback(this.Connect), socket);         }         private void btnSendFile_Click(object sender, EventArgs e)         {             using (OpenFileDialog ofd = new OpenFileDialog())             {                 if (ofd.ShowDialog() != DialogResult.OK)                 {                     return;                 }                 byte[] data = File.ReadAllBytes(ofd.FileName);                 byte[] result = new byte[data.Length + 1];                 result[0] = 3;                 Buffer.BlockCopy(data, 0, result, 1, data.Length);                 foreach (var proxSocket in ProxSocketList)                 {                     if (!proxSocket.Connected)                     {                         continue;                     }                     proxSocket.Send(result, SocketFlags.None);                 }             }         }         private void button1_Click(object sender, EventArgs e)         {             foreach (var proxSocket in ProxSocketList)             {                 if (!proxSocket.Connected)                 {                     proxSocket.Send(new byte[] { 2 }, SocketFlags.None);                 }             }         }     } }

客户端------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------


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

namespace TcpFrmClient
{
    
    public partial class Form1 : Form
    {
        public Socket sockets { get; set; }
        public Form1()
        {
            InitializeComponent();

            Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void btnConncet_Click(object sender, EventArgs e)
        {

        }

        public void Data(object socket)
        {
            var proxSocket = socket as Socket;
            byte[] data = new byte[1024 * 1024];
            int n = 0;
            while (true)
            {
                try
                {
                   n = proxSocket.Receive
                         (data, 0, data.Length, SocketFlags.None);
                }
                catch (Exception ex)
                {
                 //   TextToLog
                 //(string.Format("接收到服务器:{0}错误", proxSocket.RemoteEndPoint.ToString()));
                    Contnet();
                    return;
                }

                if (n <= 0)
                {
                   // TextToLog
                   //(string.Format("接收到服务器端:{0}正常", proxSocket.RemoteEndPoint.ToString()));
                    Contnet();  //
                    return;
                }

                if (data[0] == 1)
                {
                    string strMsg = RecieveString(data);
                  //  TextToLog
                  //(string.Format("接收到客户端:{0}的消息:{1}", proxSocket.RemoteEndPoint.ToString(), strMsg));
                }

                else if (data[0]==2)
                {
                    break;
                }

                else if (data[0] == 3)
                {
                    RecieveFile(data,n);

                }
               // string str = Encoding.Default.GetString(data);
             
              //  TextToLog
              //(string.Format("接收到客户端:{0}的消息:{1}", proxSocket.RemoteEndPoint.ToString(), str));


            }

        }


        public void RecieveFile(byte[] data,int n)
        {
            using (SaveFileDialog sfd =new SaveFileDialog())
            {
                //try
                //{
                    if (sfd.ShowDialog(this) != DialogResult.OK)
                    {
                        return;
                    }
                    byte[] fileData = new byte[n - 1];
                    Buffer.BlockCopy(data, 1, fileData, 0, n - 1);
                    File.WriteAllBytes(sfd.FileName, fileData);
                //}
                //catch (Exception ex)
                //{

                //   // MessageBox.Show(".......");
                //}
               
              
            }

        }

        public string RecieveString(byte[] datas)
        {
            string str = Encoding.Default.GetString(datas, 1, datas.Length - 1);
            return str;
        }

        private void Contnet()
        {
            try
            {
                if (sockets.Connected)
                {
                    sockets.Shutdown(SocketShutdown.Both);
                    sockets.Close(100);
                }
            }
            catch (Exception ex)
            {


            }

        }

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

                }), txt);

                //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)
        {
            if (sockets.Connected)
            {
                byte[] data = Encoding.Default.GetBytes(txtMsg.Text);



                sockets.Send(data, 0, data.Length, SocketFlags.None);
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Socket socket = new Socket
               (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            sockets = socket;

            try
            {
                socket.Connect
              (new IPEndPoint(IPAddress.Parse("ip地址"),65530));
            }
            catch (Exception ex)
            {
                MessageBox.Show("....");
                return;
            }
            Thread thread = new Thread(new ParameterizedThreadStart(Data));
            thread.IsBackground = true;
            thread.Start(sockets);




        }

        private void txtLog_TextChanged(object sender, EventArgs e)
        {

        }

      
    }
}