SOCKET 发送消息给 监听端, 监听端返回 消息给 发送端发送端怎样接受啊还是 发送端也要写监听

解决方案 »

  1.   

    可以看看MSDN中给出的例子public static int SendReceiveTest1(Socket server)
    {
        byte[] msg = Encoding.UTF8.GetBytes("This is a test");
        byte[] bytes = new byte[256];
        try 
        {
            // Blocks until send returns.
            int i = server.Send(msg);
            Console.WriteLine("Sent {0} bytes.", i);        // Get reply from the server.
            i = server.Receive(bytes);
            Console.WriteLine(Encoding.UTF8.GetString(bytes));
        }
        catch (SocketException e)
        {
            Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode);
            return (e.ErrorCode);
        }
        return 0;
    }
      

  2.   

    就是说,send以后,就可以recieve了,如果你要实现异步的通信,那么就会复杂一点要用beginsend了。
      

  3.   

    在CodeProject上有一个不错的例子,虽然说明是用英文写的,但是很详尽,用金山词霸查下单词很容易看懂的,你可以参考下
    http://www.codeproject.com/KB/IP/socketsincs.aspx
      

  4.   

    发送端不用写监听,用个循环来接受就可以了。。        static void Main(string[] args)
            {
                try
                {
                    //建立客户端套接字
                    Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
                    //绑定到127.0.0.1地址的3000端口
                    IPAddress localAddr = IPAddress.Parse("127.0.0.1");
                    IPEndPoint endPt = new IPEndPoint(localAddr, 3000);
                    client.Connect(endPt);                //如果缓冲区有消息进入
                    byte[] buffer = new byte[10];
                    if (client.Receive(buffer) > 0)
                    {
                        //显示接收到的数据信息
                        Console.WriteLine("连接上...");
                        Console.WriteLine("从服务器接收数据...");
                        //缓冲区数据不为0时
                        int end = 5;
                        while (buffer[end] != 0)
                        {
                            //显示出缓冲区的数据
                            Console.WriteLine(buffer[end]);
                            //标记加1
                            end++;
                        }
                        //提示连接即将断开
                        Console.WriteLine("连接断开...");
                        //输出数据后断开连接
                        client.Shutdown(SocketShutdown.Both);
                        client.Close();
                    }                Console.ReadLine();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("发生异常:" + ex.Message);
                    Console.ReadLine();
                }
            }