首页 > 代码库 > Socket代码

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 =http://www.mamicode.com/ 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)        {        }    }}