码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-01-22 23:22:20      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:

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

程序如图

技术分享

主要代码

    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实现的两个程序的通信

标签:

原文地址:http://www.cnblogs.com/yanshanshuo/p/4242857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!