Socket代码

服务器端

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

namespace DMServer
{
    public partial class Form1 : Form
    {
        Thread TempThread;
        Socket server;

        string labelText = string.Empty;

        public string LabelText
        {
            get { return labelText; }
            set 
            {
                labelText = value;
            }
        }

        public static ManualResetEvent allDone = new ManualResetEvent(false);

        bool isDo = false;

        public Form1()
        {
            InitializeComponent();
        }

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

        /// <summary>
        /// 用这个方法,另一个经测试是不好使的
        /// </summary>
        public void StartReceive() 
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            bool isGo = true;
            server.Bind(new IPEndPoint(IPAddress.Parse("192.168.10.128"), 3001));   //这里要写客户端访问的地址
            server.Listen(10);
            Box box = new Box();
            while (isGo) 
            {
                try
                {
                    Socket s = server.Accept();
                    string content = string.Empty;
                    byte[] bs = new byte[s.Available];

                    int num = s.Receive(bs);

                    content += Encoding.ASCII.GetString(bs);

                    s.Send(Encoding.ASCII.GetBytes("ok"));
                    if (content.Equals("ABCD123")) 
                    {
                        isGo = false;
                    }
                }
                catch (Exception ex)
                {
                    
                }
                
            }

            server.Close();
        }

        /// <summary>
        /// 不好使
        /// </summary>
        public void StartReceive1()
        {
            server.Bind(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 3001));
            server.Listen(10);
            Box box = new Box();
            box.WorkSocket = server;
            while (true) 
            {
                allDone.Reset();
                server.BeginAccept(new AsyncCallback(ConnClient), box);
                allDone.WaitOne();
            }
        }

        public void ConnClient(IAsyncResult ar) 
        {
            Socket socket = ((Box)ar.AsyncState).WorkSocket;
            Socket client = socket.EndAccept(ar);

            Box box = new Box();
            box.WorkSocket = client;

            client.BeginReceive(box.Bytes, 0, box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
        }

        public void Receive(IAsyncResult ar) 
        {
            string content = string.Empty;

            Box box = (Box)ar.AsyncState;

            Socket handler = box.WorkSocket;

            int byteread = handler.EndReceive(ar);

            if (byteread > 0) 
            {
                box.Bulider.Append(Encoding.ASCII.GetString(box.Bytes, 0, byteread));

                content = box.Bulider.ToString();

                if (content.IndexOf("") > -1)
                {
                    Send(handler, "ok");
                }
                else 
                {
                    handler.BeginReceive(box.Bytes, 0, box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
                }
            }
        }

        private static void Send(Socket handler, String data)
        {
            // 消息格式转换.
            byte[] byteData = Encoding.ASCII.GetBytes(data);

            // 开始发送数据给远程目标.
            handler.BeginSend(byteData, 0, byteData.Length, 0,
                new AsyncCallback(SendCallback), handler);
        }

        private static void SendCallback(IAsyncResult ar)
        {

            // 从state对象获取socket.
            Socket handler = (Socket)ar.AsyncState;

            //完成数据发送
            int bytesSent = handler.EndSend(ar);

            handler.Shutdown(SocketShutdown.Both);
            handler.Close();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                socket.Connect(IPAddress.Parse("192.168.10.128"), 3001);
                socket.Send(Encoding.ASCII.GetBytes("ABCD123"));
            }
            catch (Exception ex)
            {
                
            }
            socket.Close();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            TempThread = new Thread(new ThreadStart(StartReceive));
            TempThread.Start();
        } 
    }
}

客户端

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

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse("192.168.10.128");

            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                client.Connect(ip, 3001);

            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败!");
                return;
            }

            try
            {
                client.Send(Encoding.ASCII.GetBytes(this.textBox1.Text));
            }
            catch (Exception)
            {
                client.Shutdown(SocketShutdown.Both);
                client.Close();
                return;
            }

            Box box = new Box();

            box.WorkSocket = client;

            client.BeginReceive(box.Bytes, 0, box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
        }

        public void Receive(IAsyncResult ar) 
        {
            string content = string.Empty;

            Box box = (Box)ar.AsyncState;

            Socket client = box.WorkSocket;

            int length = client.EndReceive(ar);

            if (length > 0) 
            {
                box.Builder.Append(Encoding.ASCII.GetString(box.Bytes, 0, length));

                content = box.Builder.ToString();

                if (content.IndexOf("") > -1)
                {
                    MessageBox.Show(content);
                    client.Close();
                }
                else 
                {
                    client.BeginReceive(box.Bytes, 0, box.Bytes.Length, SocketFlags.None, new AsyncCallback(Receive), box);
                }
            }
        }

        public class Box 
        {
            Socket workSocket;

            public Socket WorkSocket
            {
                get { return workSocket; }
                set { workSocket = value; }
            }

            byte[] bytes = new byte[1024];

            public byte[] Bytes
            {
                get { return bytes; }
                set { bytes = value; }
            }

            StringBuilder builder = new StringBuilder();

            public StringBuilder Builder
            {
                get { return builder; }
                set { builder = value; }
            }
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
    }
}

 实际应用服务器端的开启方法,注意进程休眠的位置是为了解决运行太快接受不到传过来的数据的问题:

public void Start(object port) 
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            bool isGo = true;
            IPAddress ip = Dns.GetHostAddresses(Dns.GetHostName())[0];
            server.Bind(new IPEndPoint(ip, int.Parse(port.ToString())));
            server.Listen(10);
            while (isGo)
            {
                try
                {
                    s = server.Accept();
                    Thread.Sleep(10);   //这里要注意,服务器端休眠的时间一定要比客户端少,否则和客户端一样或者大会导致客户端接收不到数据,不休眠自己会接收不到数据。
                    s.SendTimeout = 100000;
                    string content = "";
                    byte[] bytes = new byte[s.Available];
                    int num = s.Receive(bytes, 0, bytes.Length, SocketFlags.None);

                    content = Encoding.UTF8.GetString(bytes);

                    if (content.Equals("conn"))
                    {
                        s.Send(Encoding.UTF8.GetBytes("Data Source=" + ip.ToString() + ";Initial Catalog=DM;Persist Security Info=True;User ID=dm;Password=dm"));
                    }
                    if (content.Equals("Close"))
                    {
                        isGo = false;
                    }
                }
                catch (Exception ex)
                {

                }
            }
            s.Close();
            server.Close();
        }

这是修改后的客户端接受代码:

private void button1_Click(object sender, EventArgs e)
        {
            IPAddress ip = IPAddress.Parse("192.168.10.128");

            Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            try
            {
                client.Connect(ip, 3001);

            }
            catch (Exception ex)
            {
                MessageBox.Show("连接失败!");
                return;
            }

            try
            {
                client.Send(Encoding.UTF8.GetBytes(this.textBox1.Text));
            }
            catch (Exception)
            {
                client.Shutdown(SocketShutdown.Both);
                client.Close();
                return;
            }
            string content = string.Empty;
            int num = 0;
            Thread.Sleep(20);
            byte[] b = new byte[client.Available];
            num = client.Receive(b, 0, b.Length, SocketFlags.None);
            content = Encoding.UTF8.GetString(b);
            MessageBox.Show(content);
            client.Close();
            client.Dispose();
        }
原文地址:https://www.cnblogs.com/wpcnblog/p/3910659.html