利用Socket实现的两个程序的通信

写的也很简单,自己觉得挺有意思了

程序如图

利用Socket实现的两个程序的通信_第1张图片

主要代码

    public class Message
    {
        Form1 mainfrom = null;
        public Message() { }
        public Message(Form1 form)
        {
            mainfrom = form;
        }
        public bool StartReceive(int port)
        {
            try
            {
                IPEndPoint iep = new IPEndPoint(IPAddress.Loopback, port);
                Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                tcpServer.Bind(iep);
                tcpServer.Listen(100);
                tcpServer.BeginAccept(new AsyncCallback(Accept), tcpServer);
                return true;
            }
            catch (Exception ex) { return false; }
        }

        private void Accept(IAsyncResult ia)
        {
            Socket socket = ia.AsyncState as Socket;
            var client = socket.EndAccept(ia);
            byte[] buf = new byte[1024];
            socket.BeginAccept(new AsyncCallback(Accept), socket);
            StateObject state = new StateObject();
            state.workSocket = client;
            try
            {
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(Receive), state);
            }
            catch (Exception ex)
            {
                //Console.WriteLine("监听请求时出错:\r\n" + ex.ToString());
            }
        }

        private void Receive(IAsyncResult ia)
        {
            StateObject state = ia.AsyncState as StateObject;
            if (state == null)
            {
                return;
            }
            Socket client = state.workSocket;
            if (client == null)
            {
                return;
            }
            try
            {
                int count = client.EndReceive(ia);
                if (count > 0)
                {
                    try
                    {
                        client.BeginReceive(state.buffer, 0, StateObject.BufferSize, SocketFlags.None, new AsyncCallback(Receive), client);
                        string context = Encoding.GetEncoding("gb2312").GetString(state.buffer, 0, count);
                        //显示接收消息
                        mainfrom.LoginFormTextChange(context);
                    }
                    catch (Exception ex)
                    {
                        //Console.WriteLine("接收的数据出错:\r\n{0}", ex.ToString());
                    }
                }
            }
            catch (Exception err)
            {

            }
        }

        public void SendMessage(int port, string m)
        {
            System.Text.Encoding CharSet = System.Text.Encoding.GetEncoding("gb2312");
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                tcpClient.Connect(IPAddress.Loopback, port);
                string sendmsg = m;
                byte[] buff = CharSet.GetBytes(sendmsg);
                tcpClient.Send(buff, buff.Length, 0);
            }
            catch (SocketException e)
            {
            }
        }
    }

    public class StateObject
    {
        // Client  socket.
        public Socket workSocket = null;
        // Size of receive buffer.
        public const int BufferSize = 1024;
        // Receive buffer.
        public byte[] buffer = new byte[BufferSize];
        // Received data string.
        public StringBuilder sb = new StringBuilder();
    }

源码 http://yun.baidu.com/s/1i39XtjR

你可能感兴趣的:(socket)